Android Bluetooth with Examples
In android, Bluetooth is a communication network protocol, which allows devices to connect wirelessly to exchange the data with other Bluetooth devices.
Generally, in android applications by using Bluetooth API’s we can implement Bluetooth functionalities, such as searching for the available Bluetooth devices, connecting with the devices and managing the data transfer between devices within the range.
By using android Bluetooth API’s in android applications, we can perform the following functionalities.
- Scan for the available Bluetooth devices within the range
- Use local Bluetooth adapter for paired Bluetooth devices
- Connect to other devices through service discovery
- Transfer data to and from other devices
- Manage multiple connections
To transfer the data between two Bluetooth devices first, they must establish a communication channel using the pairing process. The devices which we are going to pair must be discoverable and should accept the incoming connection requests. Generally, the devices will find discoverable devices using a service discovery process. Once the device accepts the pairing request, the two devices will exchange security keys to complete the bonding process and the devices will cache these security keys for later use.
Once the pairing and bonding process completes, the devices are ready to exchange the required information. When the session is complete, the device that initiated the pairing request will release the channel that linked to the discoverable device. The two devices remain bonded, so they can reconnect automatically during a future session as long as they’re in the range of each other.
Android Set Bluetooth Permissions
To use Bluetooth features in our android applications, we must need to add multiple permissions, such as BLUETOOTH and ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION in our manifest file.
Permission | Description |
---|---|
BLUETOOTH | We need this permission to perform any Bluetooth communication, such as requesting a connection, accepting a connection, and transferring data. |
LOCATION | We need this permission because the Bluetooth scans can be used to gather the information about the location of user. |
In case, if we want to discover the available Bluetooth devices or manipulate Bluetooth settings from our app, we need to define BLUETOOTH_ADMIN permission.
Following is the example of defining the Bluetooth permissions in android manifest file.
Android BluetoothAdapter Class
In android, we can perform Bluetooth related activities by using BluetoothAdapter class in our applications.
By using BluetoothAdapter object, we can interact with device’s Bluetooth adapter to perform Bluetooth related operations. In case, if device does not contain any Bluetooth adapter, then it will return null.
Following is the code snippet to initialize BluetoothAdapter class and to know whether the Bluetooth is supported on the device or not.
BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();
if (bAdapter== null )
// Device won’t support Bluetooth
>
If you observe above code snippet, we used the getDefaultAdapter() method of BluetoothAdapter class, which will return whether the device contains Bluetooth adapter or not.
In case if getDefaultAdapter() method returns NULL, then the device does not support Bluetooth and we can disable all Bluetooth features.
Android Enable or Disable Bluetooth
If Bluetooth is supported but disabled, then the isEnabled() method will return false and we can request the user to enable Bluetooth without leaving our application by using startActivityForResult() method with ACTION_REQUEST_ENABLE intent action parameter.
Following is the code snippet to enable a Bluetooth by using BluetoothAdapter parameter ACTION_REQUEST_ENABLE.
if (!bAdapter.isEnabled())
Intent eintent = new Intent(BluetoothAdapter. ACTION_REQUEST_ENABLE );
startActivityForResult(eintent, intVal);
>
If you observe above code snippet, we used startActivityForResult() method with ACTION_REQUEST_ENABLE intent action parameter to enable a Bluetooth.
The second parameter intVal in startActivityForResult() method is a locally defined integer that must be greater than 0 and the system will return this parameter back to us during onActivityResult() implementation as a requestCode parameter.
To know more about to TURN ON / OFF Bluetooth in android applications, check this Android Bluetooth Turn ON / OFF with Examples.
Android Enable Discoverability
To make the device discoverable to other devices, we need to start the new activity by calling startActivityForResult(intent, int) with the ACTION_REQUEST_DISCOVERABLE intent.
Following is the code snippet to enable the system’s discoverable mode to make sure that the device discoverable to other devices.
Intent dIntent = new Intent(BluetoothAdapter. ACTION_REQUEST_DISCOVERABLE );
dIntent.putExtra(BluetoothAdapter. EXTRA_DISCOVERABLE_DURATION , 300 );
startActivity(dIntent);
If you observe above code snippet, we are making sure our device discoverable to other devices using ACTION_REQUEST_DISCOVERABLE. By default, the device becomes discoverable for 120 seconds. We can extend the device discoverable duration up to 3600 seconds (1 hour), by adding the EXTRA_DISCOVERABLE_DURATION extra.
To know more about device discoverability, check this Android Bluetooth Device Discoverability with Examples.
Android List Paired Devices
By using the BluetoothAdapter method getBondedDevices(), we can get the Bluetooth paired devices list.
Following is the code snippet to get all paired devices with name and MAC address of each device.
// Get paired devices.
Set pairedDevices = bAdapter.getBondedDevices();
if (pairedDevices.size() > 0 ) // There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
>
>
If you observe above code, we are getting the Bluetooth paired devices name and mac address by using BluetoothDevice object.
To know more about Bluetooth pair devices, check this Android Bluetooth List Pair Devices with Examples.
This is how we can use Bluetooth in android applications to allow a devices to connect wirelessly to exchange the data with other Bluetooth devices.
Set up Bluetooth
Before your app can communicate over Bluetooth or Bluetooth Low Energy, you need to verify that Bluetooth is supported on the device, and if it is, ensure that it is enabled. Note that this check is only necessary if the android:required attribute in the manifest file entry is set to false .
If Bluetooth isn’t supported, then you should gracefully disable any Bluetooth features. If Bluetooth is supported, but disabled, then you can request that the user enable Bluetooth without leaving your app.
The first step is adding the Bluetooth permissions to your manifest file in order to use the following APIs.
Once the permissions are in place, Bluetooth setup is accomplished in two steps using the BluetoothAdapter :
- Get the BluetoothAdapter . The BluetoothAdapter is required for any and all Bluetooth activity. The BluetoothAdapter represents the device’s own Bluetooth adapter (the Bluetooth radio). To get a BluetoothAdapter , you first need to have a Context . Use this context to obtain an instance of the BluetoothManager system service. Calling BluetoothManager#getAdapter will give you a BluetoothAdapter object. If getAdapter() returns null, then the device doesn’t support Bluetooth. For example:
Kotlin
val bluetoothManager: BluetoothManager = getSystemService(BluetoothManager::class.java) val bluetoothAdapter: BluetoothAdapter? = bluetoothManager.getAdapter() if (bluetoothAdapter == null) < // Device doesn't support Bluetooth >
Java
BluetoothManager bluetoothManager = getSystemService(BluetoothManager.class); BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter(); if (bluetoothAdapter == null) < // Device doesn't support Bluetooth >
Kotlin
if (bluetoothAdapter?.isEnabled == false)
Java
if (!bluetoothAdapter.isEnabled())
A dialog appears requesting user permission to enable Bluetooth, as shown in figure 1. If the user grants permission, the system begins to enable Bluetooth, and focus returns to your app once the process completes (or fails).
Figure 1. The enabling Bluetooth dialog.
The REQUEST_ENABLE_BT constant passed to startActivityForResult() is a locally-defined integer that must be greater than or equal to 0. The system passes this constant back to you in your onActivityResult() implementation as the requestCode parameter.
If enabling Bluetooth succeeds, your activity receives the RESULT_OK result code in the onActivityResult() callback. If Bluetooth was not enabled due to an error (or the user responded «Deny») then the result code is RESULT_CANCELED .
Optionally, your app can also listen for the ACTION_STATE_CHANGED broadcast intent, which the system broadcasts whenever the Bluetooth state changes. This broadcast contains the extra fields EXTRA_STATE and EXTRA_PREVIOUS_STATE , containing the new and old Bluetooth states, respectively. Possible values for these extra fields are STATE_TURNING_ON , STATE_ON , STATE_TURNING_OFF , and STATE_OFF . Listening for this broadcast can be useful if your app needs to detect runtime changes made to the Bluetooth state.
Tip: Enabling discoverability automatically enables Bluetooth. If you plan to consistently enable device discoverability before performing Bluetooth activity, you can skip step 2 in the earlier steps.
Once Bluetooth is enabled on the device, you can use both Bluetooth classic and Bluetooth Low Energy.
Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
Last updated 2023-02-01 UTC.