due to the recent development of Android related stuff, learn some of the source code and other people's blog, now Android Bluetooth communication summarize here, the following is a Bluetooth client and server implementation examples to explain to everyone.
1. using Bluetooth responses permissions
2. configure the local Bluetooth module
Here we must first understand the Bluetooth operating a core class BluetoothAdapter
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
//直接打开系统的蓝牙设置面板
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 0x1);
//直接打开蓝牙
adapter.enable();
//关闭蓝牙
adapter.disable();
//打开本机的蓝牙发现功能(默认打开120秒,可以将时间最多延长至300秒)
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//设置持续时间(最多300秒)Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
3. search for Bluetooth devices
Use BluetoothAdapter the startDiscovery () method to search for Bluetooth devices
startDiscovery () method is an asynchronous method call will return immediately. This method will conduct a search for other Bluetooth devices, the process will last 12 seconds. This method is called, the search process is actually carried out in a System Service, so you can call cancelDiscovery () method to stop the search (This method can be called when not running discovery request).
Discoveryrequest, the system began to search for Bluetooth devices, in this process, the system will send the following three broadcasters:
ACTION_DISCOVERY_START: Start search
ACTION_DISCOVERY_FINISHED: search ends
ACTION_FOUND: the device is found, the Intent contains two extra fields: EXTRA_DEVICE and EXTRA_CLASS, each containing BluetooDevice and BluetoothClass.
we can register yourself to receive the appropriate response BroadcastReceiver broadcast, in order to achieve some features
// 创建一个接收ACTION_FOUND广播的BroadcastReceiver
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// 发现设备
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 从Intent中获取设备对象
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 将设备名称和地址放入array adapter,以便在ListView中显示
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
// 注册BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // 不要忘了之后解除绑定
4. Bluetooth Socket Communications
If you intend to suggest a connection between two Bluetooth devices, you must implement server-side and client-side mechanisms. When two devices on the same RFCOMM channel, respectively have a connection BluetoothSocket, the two devices can be said that a connection is established.
server device and the client device gets BluetoothSocket approach is different. Server device is accepted an incoming connection to get, but it is the client device to the server by opening an RFCOMM channel to obtain.
server side implementation
by calling BluetoothAdapter the listenUsingRfcommWithServiceRecord (String, UUID) method to obtain BluetoothServerSocket (UUID is used between the client and server-side pairing)
call BluetoothServerSocket the accept () method listens for connection requests, if the request is received, it returns a BluetoothSocket instance (This method is the block method, should be placed in the new thread)
If you do not want to accept another connection, the call BluetoothServerSocket the close () method to release resources (call the method, previously obtained BluetoothSocket instance does not close. RFCOMM a moment but only allows one channel, there is a connection , then in general accept a connection, then close out BluetoothServerSocket)
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(socket);
mmServerSocket.close();
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
client implementation
obtained by searching the server BluetoothService
call BluetoothService the listenUsingRfcommWithServiceRecord (String, UUID) method to get BluetoothSocket (UUID should be the same as the server UUID)
call BluetoothSocket the connect () method (the method for the block method), if the UUID UUID match with the server, and the connection is server-side accept, then the connect () method returns
Note: In the call connect () method, you should determine the current no search equipment, otherwise the connection will become very slow and prone to failure
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
connection management (data communications)
respectively, through BluetoothSocket the getInputStream () and getOutputStream () method to get the InputStream and OutputStream
use read (bytes []) and write (bytes []) method to read and write, respectively,
Note: read (bytes []) method will always block, know the information read from the stream, and write (bytes []) method is not always a block (such as failure to make timely read on another device or intermediate buffer Area full case, write method block)
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main Activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main Activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
没有评论:
发表评论