SoFunction
Updated on 2025-03-04

Detailed explanation of the usage process of Android Bluetooth technology

In the previous article, I introduced it to youFirst experience of Android Bluetooth technologyInterested friends can click to learn more about the relevant content.

1: Communication between Bluetooth devices mainly includes four steps

Set up Bluetooth devices
Looking for possible or matching devices in the LAN
Connecting the device
Data transmission between devices

Two: Specific programming implementation

1. Activate Bluetooth function

First, the Bluetooth adapter BluetoothAdapter is obtained by calling the static method getDefaultAdapter(). If the return is empty, the execution cannot be continued. For example:

BluetoothAdapter mBluetoothAdapter = ();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}

Secondly, call isEnabled() to query the status of the current Bluetooth device. If it returns to false, it means that the Bluetooth device is not enabled. Next, you need to encapsulate an ACTION_REQUEST_ENABLE request into the intent and call the startActivityForResult() method to enable the Bluetooth device, for example:

if (!()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

2. Find the device

Using the methods in the BluetoothAdapter class, you can find remote devices (within about ten meters) or query other devices that have matched (or bound) on your phone. Of course, you need to make sure that the other party’s Bluetooth device has been turned on or has enabled the “discovered enable” function (the other party’s device can be discovered is a prerequisite for you to initiate the connection). If the device can be discovered, some device information from the other party will be fed back, such as name, MAC address, etc. Using this information, your device can choose to initialize a connection to the other party.

If you are connecting to the device for the first time, a pairing request will be automatically displayed to the user. When the device is paired, some of its basic information (mainly the name and MAC) is saved and can be read using the Bluetooth API. Use a known MAC address to initiate a connection request to the remote Bluetooth device.
The difference between a well-matched device and a connected device: a well-matched device just means that the other party’s device has discovered your existence, has a common identification code, and can be connected. Connected: Indicates that the current device shares an RFCOMM channel and data can be exchanged between the two. That is to say, the Bluetooth device must be paired before establishing the RFCOMM channel.

3. Query the matching equipment

Before establishing a connection, you must first query the paired Bluetooth device set to select a device to communicate. For example, you can query all paired Bluetooth devices and print them with an array adapter:

Set<BluetoothDevice> pairedDevices =();
// If there are paired devices
if (() > 0) {
//Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
(() + "\n" + ());
}
}

It is enough to establish a Bluetooth connection with only the MAC address.

4. Scan the device

To scan the device, you only need to call the startDiscovery() method. The scanning process lasts about 12 seconds. In order to enable the ACTION_FOUND action, the application needs to register a BroadcastReceiver to receive the information scanned by the device. For each device, the system broadcasts the ACTION_FOUND action.

// Use ACTION_FOUND to register the broadcast receiver for actionprivate final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = ();
// Discover equipmentif (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get Bluetooth device from IntentBluetoothDevice device = (BluetoothDevice.EXTRA_DEVICE);
// Add name and address to device adapter(() + "\n" + ());
}
}
};
//Register broadcast receiverIntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); //existonDestroyRemember to log out of the broadcast receiver when

5. Enable to be discovered

If you want your device to be discovered by other devices, just encapsulate the ACTION_REQUEST_DISCOVERABLE action in an intent and call the startActivityForResult(Intent, int) method. It will enable your device to be discovered without causing your application to exit. By default, the enable time is 120 seconds. Of course, you can change the enable time by adding the EXTRA_DISCOVERABLE_DURATION field (maximum not exceeding 300 seconds). For example:

Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);

After running this code, a dialog box will pop up to prompt you to enable the device to be discovered (in this process, if your Bluetooth function is not enabled, the system will enable it for you), and if you are ready to find a connection to the remote device, you do not need to enable the device to be discovered, because this function is only needed when your application is the server side.

6. Connect the device

In an application, if you want to establish a connection between two Bluetooth devices, you must implement the client and server code (because any device must be a server or client). One enables the service to listen, and the other initiates the connection request (using the MAC address of the server-side device). When they all have a Bluetooth socket on the same RFECOMM channel, they can be considered to have been connected. Servers and clients use different ways or their Bluetooth sockets. When a connection is heard, the server obtains the Bluetooth socket. When the client can open a FRCOMM channel to the server, the client obtains the Bluetooth socket.

Note: During this process, if the two Bluetooth devices have not been paired, the Android system will notify the user through a notification or dialog box. RFCOMM connection requests block before user selections.

7. Server connection

When you want to connect two devices, one must serve as a server (by holding an open BluetoothServerSocket), which aims to listen for foreign connection requests. When listening, it provides a BluetoothSocket on the connection to the client. When the client gets the BluetoothSocket from the BluetoothServerSocket, it can destroy the BluetoothServerSocket unless you also want to listen for more connection requests.
Basic steps to establish a service socket and listening connection:
First, the BluetoothServerSocket object is obtained by calling the listenUsingRfcommWithServiceRecord(String, UUID) method. The parameter String represents the name of the service. The UUID represents an identity for the connection with the client (a string ID in 128-bit format, equivalent to the PIN code). The UUID must match both parties before the connection can be established.

Secondly, call the accept() method to listen for possible connection requests. After listening, return a Bluetooth socket on the connection BluetoothSocket.
Finally, after listening to a connection, you need to call the close() method to close the listener. (Generally, point-to-point transmission is between Bluetooth devices)
Note: The accept() method should not be placed in the main Activity, because it is a blocking call (the program stops there until the connection request is heard). The solution is to create a new thread to manage. For example:

8. Client connection

In order to initialize a connection to a remote device, you need to first obtain a BluetoothDevice object representing the device. Use the BluetoothDevice object to obtain the BluetoothSocket and initialize the connection. The specific steps are:

Use the method createRfcommSocketToServiceRecord(UUID) in the BluetoothDevice object to obtain the BluetoothSocket. UUID is the matching code. Then, call the connect() method. If the remote device receives the connection, they will share the RFFCOMM channel during communication and connect back.

Note: The conncet() method is also a blocking call, and it is generally established to call the method in an independent thread. Connect() should not be initiated during device discovery, as this will significantly slow down the connection fails. And when the data transmission is completed, only the close() method can be called to close the connection, which can save internal resources of the system.

9. Manage connections

When the device is connected, each device has its own BluetoothSocket. This enables data sharing between devices.
First, the input and output stream is obtained by calling the getInputStream() and getOutputStream() methods.
Then read or write data by calling read(byte[]) and write(byte[]).
Implementation details: I thought that read and write operations were blocking calls, and a dedicated thread was needed to be established to manage it.

10. Permission settings

<uses-permissionandroid:name=".BLUETOOTH_ADMIN" />
<uses-permissionandroid:name="" />

The above is a detailed explanation of the usage process of Android Bluetooth technology shared by the editor. I hope it will be helpful to everyone.