-
Notifications
You must be signed in to change notification settings - Fork 6.2k
Connectivity using the Bluetooth API
The Android platform includes support for the Bluetooth network stack, which allows a device to wirelessly exchange data with other Bluetooth devices. The application framework provides access to the Bluetooth functionality through the Android Bluetooth APIs. These APIs let applications wirelessly connect to other Bluetooth devices, enabling point-to-point and multipoint wireless features.
Using the Bluetooth APIs, an Android application can perform the following:
- Scan for other Bluetooth devices
- Query the local Bluetooth adapter for paired Bluetooth devices
- Connect to other devices through service discovery
- Transfer data to and from other devices
- Manage multiple connections
In order to use Bluetooth features in your application, you must declare the appropriate permissions in your manifest. The permissions you need differ based on the API level your app targets.
For apps that target Android 12 (API level 31) or higher, declare the runtime permissions BLUETOOTH_SCAN (when looking for Bluetooth devices), BLUETOOTH_ADVERTISE (when making the device discoverable), and BLUETOOTH_CONNECT (when communicating with already-paired devices). The legacy BLUETOOTH and BLUETOOTH_ADMIN permissions should be declared with android:maxSdkVersion="30" so the system only requests them on older devices. See Bluetooth permissions for the full guidance, including when ACCESS_FINE_LOCATION is still required (e.g. when BLUETOOTH_SCAN is not annotated with usesPermissionFlags="neverForLocation").
<manifest ... >
<!-- Request legacy Bluetooth permissions on older devices. -->
<uses-permission android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />
<!-- Needed only if your app looks for Bluetooth devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<!-- Needed only if your app makes the device discoverable. -->
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<!-- Needed only if your app communicates with already-paired devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
</manifest>- Get the
BluetoothAdaptervia the systemBluetoothManager.BluetoothAdapter.getDefaultAdapter()is deprecated — go throughBluetoothManagerinstead. TheContext.getSystemService(Class)overload used in Google's snippet was added in API 23, so on projects withminSdkbelow 23 use the backwards-compatibleContextCompat.getSystemService(...)fromandroidx.core:core(shown below).
// Works on every supported API level — ContextCompat falls back to the
// String-based getSystemService(Context.BLUETOOTH_SERVICE) lookup below API 23.
BluetoothManager bluetoothManager =
ContextCompat.getSystemService(this, BluetoothManager.class);
BluetoothAdapter bluetoothAdapter =
bluetoothManager != null ? bluetoothManager.getAdapter() : null;
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
}-
Enable Bluetooth. Use the Activity Result API (
ActivityResultLauncher+registerForActivityResult(...)) —startActivityForResult(...)/onActivityResult(...)are deprecated.Declare the launcher as a field on your
AppCompatActivity(orFragment), or register it inonCreate()— registration must happen before the activity isSTARTED, so a click handler or other lifecycle-late hook is too late.// androidx.activity.result.ActivityResultLauncher // androidx.activity.result.contract.ActivityResultContracts // android.app.Activity private final ActivityResultLauncher<Intent> enableBtLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == Activity.RESULT_OK) { // Bluetooth was turned on. Continue with discovery, pairing, etc. } else { // result.getResultCode() == Activity.RESULT_CANCELED means the user // declined, or Bluetooth could not be enabled. } });
At the call site — typically a button handler or another lifecycle method that runs after the activity is created — kick off the system prompt with
launch(...):if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); enableBtLauncher.launch(enableBtIntent); }
A system dialog asks the user for permission to enable Bluetooth. When the user dismisses it (either by accepting or declining), the launcher's callback fires with an
ActivityResult:RESULT_OKif Bluetooth is now on,RESULT_CANCELEDotherwise.On Android 12 (API level 31) and higher, you must hold the runtime
BLUETOOTH_CONNECTpermission before launchingACTION_REQUEST_ENABLE— request it with aRequestPermissionlauncher first, then callenableBtLauncher.launch(...)from that permission callback.
Check out these libraries for easy handling of Bluetooth in your apps:
- Android-BluetoothSPPLibrary - Hardware developer? This is an easy way to use the Bluetooth Serial Port Profile
- RxAndroidBle - Easily handle Bluetooth Low Energy
- https://developer.android.com/develop/connectivity/bluetooth/ble/ble-overview
- http://www.tutorialspoint.com/android/android_bluetooth.htm
- https://developer.android.com/develop/connectivity/bluetooth
- http://code.tutsplus.com/tutorials/create-a-bluetooth-scanner-with-androids-bluetooth-api--cms-24084
- http://www.intorobotics.com/how-to-develop-simple-bluetooth-android-application-to-control-a-robot-remote/
- https://github.com/palaima/AndroidSmoothBluetooth
- https://github.com/DeveloperPaul123/SimpleBluetoothLibrary
Created by CodePath with much help from the community. Contributed content licensed under cc-wiki with attribution required. You are free to remix and reuse, as long as you attribute and use a similar license.
Finding these guides helpful?
We need help from the broader community to improve these guides, add new topics and keep the topics up-to-date. See our contribution guidelines here and our topic issues list for great ways to help out.
Check these same guides through our standalone viewer for a better browsing experience and an improved search. Follow us on twitter @codepath for access to more useful Android development resources.