When using mobile phones, Bluetooth communication brings us a lot of convenience. So how to develop Bluetooth in Android phones? This article explains the knowledge of Android Bluetooth development in an example way.
1. Response permissions to use Bluetooth
XML/HTML Code
<uses-permission android:name=""/> <uses-permission android:name=".BLUETOOTH_ADMIN"/>
2. Configure the Bluetooth module of this machine
Here we first need to understand a core class BluetoothAdapter operation for Bluetooth.
BluetoothAdapter adapter = (); //Open the Bluetooth settings panel of the system directly Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, 0x1); //Open Bluetooth directly (); // Turn off Bluetooth (); // Turn on the Bluetooth discovery function of this unit (120 seconds is turned on by default, and the time can be extended to up to 300 seconds) Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); (BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//Set duration(most300Second)
3. Search for Bluetooth devices
Use BluetoothAdapter's startDiscovery() method to search for Bluetooth devices.
The startDiscovery() method is an asynchronous method that will be returned immediately after being called. This method will search for other Bluetooth devices, and the process will last for 12 seconds. After this method is called, the search process is actually performed in a System Service, so you can call the cancelDiscovery() method to stop the search (the method can be called when the discovery request is not executed).
After requesting Discovery, the system starts searching for Bluetooth devices. During this process, the system will send the following three broadcasts:
ACTION_DISCOVERY_START: Start searching
ACTION_DISCOVERY_FINISHED: Search ends
ACTION_FOUND: Find the device. This Intent contains two extra fields: EXTRA_DEVICE and EXTRA_CLASS, including BluetoothDevice and BluetoothClass respectively.
We can register the corresponding one by ourselvesBroadcastReceiverto receive a response broadcast to implement certain functions.
// Create a BroadcastReceiver that receives ACTION_FOUND broadcasts private final BroadcastReceiver mReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = (); // Discover equipment if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Get device object from Intent BluetoothDevice device = (BluetoothDevice.EXTRA_DEVICE); // Put the device name and address into the array adapter to display in ListView (() + "\n" + ()); } } }; // Register BroadcastReceiver IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter); // Don't forget to unbind it later
4. Bluetooth Socket Communication
If you plan to suggest a connection between two Bluetooth devices, you must implement the server-side and client mechanism. Only when two devices have a connected BluetoothSocket under the same RFCOMM channel can these two devices establish a connection.
The ways to obtain BluetoothSockets are different from the server device and the client device. The server device is obtained by accepting an incoming connection, while the client device is obtained by opening an RFCOMM channel to the server.
Server-side implementation
Get the BluetoothServerSocket (UUID is used for pairing between the client and the server) by calling the listenUsingRfcommWithServiceRecord(String, UUID) method of BluetoothAdapter.
Call the accept() method of BluetoothServerSocket to listen for connection requests. If a request is received, a BluetoothSocket instance is returned (this method is a block method and should be placed in the new thread).
If you do not want to accept other connections, call the close() method of BluetoothServerSocket to release the resource (after calling this method, the BluetoothSocket instance obtained previously does not have close. However, since RFCOMM only allows one connection in one channel at a time, it is usually closed after accepting one connection).
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 = (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 = (); } catch (IOException e) { break; } // If a connection was accepted if (socket != null) { // Do work to manage the connection (in a separate thread) manageConnectedSocket(socket); (); break; } } } /** Will cancel the listening socket, and cause the thread to finish */ public void cancel() { try { (); } catch (IOException e) { } } }
Client implementation
Get the server-side BluetoothService through search.
Call BluetoothService's listenUsingRfcommWithServiceRecord(String, UUID) method to get the BluetoothSocket (this UUID should be the same as the server-side UUID).
Call BluetoothSocket's connect() method (this method is a block method). If the UUID matches the UUID on the server side and the connection is accepted by the server side, the connect() method returns.
Note: Before calling the connect() method, you should make sure that there is currently no search device, 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 = (MY_UUID); } catch (IOException e) { } mmSocket = tmp; } public void run() { // Cancel discovery because it will slow down the connection (); try { // Connect the device through the socket. This will block // until it succeeds or throws an exception (); } catch (IOException connectException) { // Unable to connect; close the socket and get out try { (); } 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 { (); } catch (IOException e) { } } }
5. Connection Management (Data Communication)
Get InputStream and OutputStream through the getInputStream() and getOutputStream() methods of BluetoothSocket respectively.
Use the read(bytes[]) and write(bytes[]) methods to perform read and write operations separately.
Note: the read(bytes[]) method will block all the time, knowing that information is read from the stream, while the write(bytes[]) method is not a frequent block (for example, if another device does not read in time or the intermediate buffer is full, the write method will 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 = (); tmpOut = (); } 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 = (buffer); // Send the obtained bytes to the UI Activity (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 { (bytes); } catch (IOException e) { } } /* Call this from the main Activity to shutdown the connection */ public void cancel() { try { (); } catch (IOException e) { } } }
The above is a simple sample code for the development of Android Bluetooth. We will continue to sort out relevant information in the future. Thank you for your support for this site!