Convert Figma logo to code with AI

NordicSemiconductor logoAndroid-BLE-Library

A library that makes working with Bluetooth LE on Android a pleasure. Seriously.

2,059
421
2,059
34

Top Related Projects

An Android Bluetooth Low Energy (BLE) Library with RxJava3 interface

5,333

Android Bluetooth Low Energy (BLE) Fast Development Framework. It uses simple ways to filter, scan, connect, read ,write, notify, readRssi, setMTU, and multiConnection.

React Native BLE library

Quick Overview

The Android-BLE-Library is an open-source Bluetooth Low Energy (BLE) library for Android devices, developed by Nordic Semiconductor. It simplifies the process of scanning for, connecting to, and communicating with BLE devices, providing a high-level API that abstracts many of the complexities of Android's native BLE APIs.

Pros

  • Easy-to-use, high-level API for BLE operations
  • Supports both callback and coroutine-based programming models
  • Includes features like automatic reconnection and GATT caching
  • Well-documented with extensive examples and sample applications

Cons

  • Primarily focused on Nordic Semiconductor devices, may have limited support for other manufacturers
  • Requires a minimum Android API level of 18 (Android 4.3)
  • May have a steeper learning curve for developers new to BLE concepts
  • Dependency on external libraries might increase app size

Code Examples

  1. Scanning for BLE devices:
val scanner = BluetoothLeScannerCompat.getScanner()
val settings = ScanSettings.Builder()
    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
    .build()
val filters = listOf(ScanFilter.Builder().setServiceUuid(ParcelUuid(YOUR_SERVICE_UUID)).build())

scanner.startScan(filters, settings, scanCallback)
  1. Connecting to a BLE device:
val connectionObserver = object : ConnectionObserver {
    override fun onDeviceConnecting(device: BluetoothDevice) { /* ... */ }
    override fun onDeviceConnected(device: BluetoothDevice) { /* ... */ }
    override fun onDeviceFailedToConnect(device: BluetoothDevice, reason: Int) { /* ... */ }
    override fun onDeviceReady(device: BluetoothDevice) { /* ... */ }
    override fun onDeviceDisconnecting(device: BluetoothDevice) { /* ... */ }
    override fun onDeviceDisconnected(device: BluetoothDevice, reason: Int) { /* ... */ }
}

val bleManager = BleManager.getInstance(context)
bleManager.connect(device)
    .retry(3, 100)
    .useAutoConnect(false)
    .timeout(30000)
    .done { /* Connection successful */ }
    .fail { /* Connection failed */ }
  1. Reading a characteristic:
bleManager.readCharacteristic(characteristic)
    .with { value ->
        // Handle the read value
    }
    .fail { device, status ->
        // Handle the error
    }
    .enqueue()

Getting Started

  1. Add the library to your project's build.gradle:
dependencies {
    implementation 'no.nordicsemi.android:ble:2.6.1'
}
  1. Initialize the BleManager in your Application class:
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        BleManager.getInstance(this)
    }
}
  1. Request necessary permissions in your MainActivity:
private fun requestPermissions() {
    val permissions = arrayOf(
        Manifest.permission.BLUETOOTH_SCAN,
        Manifest.permission.BLUETOOTH_CONNECT,
        Manifest.permission.ACCESS_FINE_LOCATION
    )
    ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE)
}
  1. Start scanning for devices and connect to them using the code examples provided above.

Competitor Comparisons

An Android Bluetooth Low Energy (BLE) Library with RxJava3 interface

Pros of RxAndroidBle

  • Utilizes RxJava for reactive programming, offering better handling of asynchronous operations
  • Provides a more streamlined API for BLE operations, reducing boilerplate code
  • Offers automatic connection and disconnection management

Cons of RxAndroidBle

  • Steeper learning curve for developers unfamiliar with reactive programming concepts
  • Potentially higher memory footprint due to RxJava dependency
  • May require additional configuration for optimal performance in complex scenarios

Code Comparison

Android-BLE-Library:

BluetoothDevice device = ...;
BleManager bleManager = new BleManager(context);
bleManager.connect(device)
    .done(connection -> {
        // Handle connection
    })
    .fail(error -> {
        // Handle error
    });

RxAndroidBle:

RxBleClient rxBleClient = RxBleClient.create(context);
rxBleClient.getBleDevice(deviceMacAddress)
    .establishConnection(false)
    .subscribe(
        rxBleConnection -> {
            // Handle connection
        },
        throwable -> {
            // Handle error
        }
    );

Both libraries provide BLE functionality for Android, but RxAndroidBle offers a more reactive approach with RxJava integration, while Android-BLE-Library provides a simpler, callback-based API. The choice between them depends on the project's requirements and the development team's familiarity with reactive programming concepts.

5,333

Android Bluetooth Low Energy (BLE) Fast Development Framework. It uses simple ways to filter, scan, connect, read ,write, notify, readRssi, setMTU, and multiConnection.

Pros of FastBle

  • Simpler API and easier to use for beginners
  • Faster connection and data transmission speeds
  • More comprehensive documentation and examples

Cons of FastBle

  • Less robust error handling and debugging features
  • Limited support for advanced BLE features and protocols
  • Smaller community and fewer updates compared to Android-BLE-Library

Code Comparison

FastBle:

BleManager.getInstance().connect(deviceMac, new BleGattCallback() {
    @Override
    public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
        // Handle connection success
    }
});

Android-BLE-Library:

BleManager.getInstance().connect(device)
    .retry(3, 100)
    .useAutoConnect(false)
    .timeout(30000)
    .done(device -> {
        // Handle connection success
    });

The FastBle code is more concise and straightforward, while Android-BLE-Library offers more configuration options and flexibility. Android-BLE-Library provides a fluent interface for connection settings, allowing for easier customization of connection parameters.

React Native BLE library

Pros of react-native-ble-plx

  • Cross-platform support for both iOS and Android
  • Seamless integration with React Native applications
  • Comprehensive API for BLE operations with Promise-based interface

Cons of react-native-ble-plx

  • Potentially higher learning curve for developers not familiar with React Native
  • May have performance overhead due to JavaScript bridge
  • Limited to React Native ecosystem, not suitable for native Android development

Code Comparison

Android-BLE-Library (Java):

BleManager.getInstance().connect(device)
    .retry(3, 100)
    .useAutoConnect(false)
    .timeout(30000)
    .done(device -> {
        // Handle connection success
    })
    .fail((device, status) -> {
        // Handle connection failure
    });

react-native-ble-plx (JavaScript):

device.connect()
  .then(() => device.discoverAllServicesAndCharacteristics())
  .then(() => {
    // Handle connection and discovery success
  })
  .catch((error) => {
    // Handle errors
  });

Both libraries provide methods for connecting to BLE devices, but react-native-ble-plx uses a more modern Promise-based approach, while Android-BLE-Library uses a custom callback system. The react-native-ble-plx code is more concise and follows JavaScript conventions, making it easier for web developers to understand and use.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Download

Android BLE Library

An Android library that solves a lot of Android's Bluetooth Low Energy problems.

[!Note] We're working on a new version of Bluetooth LE library, which eventually will replace this one: Kotlin BLE Library / version 2.0. Mind, that version 2 is not backward compatible version 1 or with this library.

Currently, the library is in the early development stage. It is not recommended for production use, but we encourage you to try it out and provide feedback.

The new library offers the following improvements over this one:

  • 100% Kotlin code
  • Scanning for Bluetooth LE devices (scan results as Flow)
  • Support for Bluetooth LE advertising
  • Support for mocking BLE devices (easy testing)
  • All BLE operations use suspend modifier or Flows

Read more on project's Readme file.

Importing

The library may be found on Maven Central repository. Add it to your project by adding the following dependency:

implementation 'no.nordicsemi.android:ble:2.9.0'

The last version not migrated to AndroidX is 2.0.5.

BLE library with Kotlin extension is available in:

implementation 'no.nordicsemi.android:ble-ktx:2.9.0'

To import the BLE library with set of parsers for common Bluetooth SIG characteristics, use:

implementation 'no.nordicsemi.android:ble-common:2.9.0'

For more information, read this.

An extension for easier integration with LiveData is available after adding:

implementation 'no.nordicsemi.android:ble-livedata:2.9.0'

This extension adds ObservableBleManager with state and bondingState properties, which notify about connection and bond state using androidx.lifecycle.LiveData.

Importing as a module

Clone this project and add it to your project:

  1. In settings.gradle file add the following lines:

    if (file('../Android-BLE-Library').exists()) {
        includeBuild('../Android-BLE-Library')
    }
    
  2. Sync project and build it.

    The library uses Java 1.18 features. If you're using Android Studio below Giraffe, make sure your build.gradle includes the following configuration:

        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_17
            targetCompatibility JavaVersion.VERSION_1_17
        }
        // For Kotlin projects additionally:
        kotlinOptions {
            jvmTarget = "1.17"
        }
    

Features

BleManager class provides the following features:

  1. Connection, with automatic retries
  2. Service discovery
  3. Bonding (optional) and removing bond information (using reflections)
  4. Automatic handling of Service Changed indications
  5. Device initialization
  6. Asynchronous and synchronous BLE operations using queue
  7. Splitting and merging long packets when writing and reading characteristics and descriptors
  8. Requesting MTU and connection priority (on Android Lollipop or newer)
  9. Reading and setting preferred PHY (on Android Oreo or newer)
  10. Reading RSSI
  11. Refreshing device cache (using reflections)
  12. Reliable Write support
  13. Operation timeouts (for connect, disconnect and wait for notification requests)
  14. Error handling
  15. Logging
  16. GATT server (since version 2.2)
  17. Kotlin support (coroutines, Flow, ...) (since version 2.3)

Note: The library does not provide support for scanning for Bluetooth LE devices. Instead, we recommend using Android Scanner Compat Library which brings almost all recent features, introduced in Lollipop and later, to the older platforms.

Recent changes

See Releases for details. Below is short summary:

Version 2.7
  1. Library has been migrated to Java 17 due to minimum supported version in Android Studio Giraffe.
Version 2.6
  1. getGattCallback() method has been deprecated. Instead, simply move the inner methods to the BleManager class. See this PR.
  2. Support for server only implementation using attachClientConnection(BluetoothDevice). Call it instead of connect(BluetoothDevice) to use the device as server-only.
  3. Data provider for read requests (server side) was added.
  4. Cancellation support for flows and suspended methods added to :ble-kts.
Version 2.4
  1. More :ble-ktx extensions.
    1. .suspendForResponse() and .suspendForValidResponse() extension methods added to read and write requests.
    2. .asResponseFlow() and .asValidResponseFlow() methods added to ValueChangedCallback.
    3. .stateAsFlow() and .bondingStateAsFlow() in BleManager now return the same flow when called multiple times.
    4. Progress indications for split outgoing data and merged incoming data can be observed as Flow using splitWithProgressFlow(...) and mergeWithProgressFlow(...).
  2. A new then(...) method added to ValueChangedCallback which will be called when the callback has been unregistered, or the device has invalidated services (i.e. it has disconnected). Useful to release resources.
  3. A new option to remove a handler from each Request using setHandler(null), which will make the callbacks called immediately from the worker looper.
  4. Option to filter logs by priority. By default only logs on Log.INFO or higher will now be logged. Use getMinLogPriority() to return a different value if needed. Logs with lower priority will not be produced at all, making the library less laggy (parsing incoming data to hex takes notable time).
  5. Added support for Big Endian format types with the new Data.FORMAT_xxx_BE types. Also, FORMAT_xxx have been deprecated in favor of FORMAT_xxx_LE.
  6. All user callbacks (before, with, then, fail, ...) are now wrapped in try-catch blocks.
Version 2.3
  1. :ble-ktx module added with support for coroutines and Flow.

    1. .suspend() methods added in Requests.
    2. asFlow() method added to ValueChangedCallback.
    3. Connection and bonding state available as Flow.
    4. New helper methods to get a BluetoothGattCharacteristic with given required properties and instance id added to BluetoothGattService.
  2. JsonMerger class added, which should help with use cases when a device sends a JSON file in multiple packets.

  3. :ble-livedata migrated to Java with some API changes, as sealed classes are no longer available.

  4. Support for new onServicesChanged() callback, added in API 31 (Android 12).

  5. Option to cancel pending Bluetooth LE connection using ConnectRequest.cancelPendingConnection().

    When using coroutines, use .suspend() method in Request, instead of enqueue() or await().

    To register to notifications and indications (or incoming write requests for server) use

    setNotificationCallback(characteristic)
       .merge(JsonMerger()) // Example of how to use JsonMerger, optional
       .asFlow()
    
Version 2.2
  1. GATT Server support. This includes setting up the local GATT server on the Android device, new requests for server operations:
    • wait for read,
    • wait for write,
    • send notification,
    • send indication,
    • set characteristic value,
    • set descriptor value.
  2. New conditional requests:
    • wait if,
    • wait until.
  3. BLE operations are no longer called from the main thread.
  4. There's a new option to set a handler for invoking callbacks. A handler can also be set per-callback.

Version 2.2 breaks some API known from version 2.1.1. Check out migration guide.

Usage

See Usage for more details.

Examples

Trivia game

The Trivia game is an example demonstrating client and server.

GATT Client Example

Please refer to the examples/ble-gatt-client folder for a project that illustrates the GATT server provided as a foreground service. There's a simple UI with a text field to update with the value of a characteristic that can be read and subscribed to. This characteristic also demands encryption as an illustration of best-practice.

You can run this client on one device and a complimenting server on another (see the next section).

Note: This project is not maintained actively. It is provided as an example only and may not be migrated to latest version.

GATT Server example

Starting from version 2.2 you may now define and use the GATT server in the BLE Library.

Please refer to the examples/ble-gatt-server folder for a project that illustrates the GATT server provided as a foreground service. There's a simple UI with a text field to update the value of a characteristic that can be read and subscribed to. This characteristic also demands encryption as an illustration of best-practice.

Note: This project is not maintained actively. It is provided as an example only and may not be migrated to latest version.

More examples

Find the simple example here Android nRF Blinky.

For an example how to use it from a ViewModel or a Service, check nRF Toolbox.

Version 1.x

The BLE library v 1.x is no longer supported. Please migrate to 2.x for bug fixing releases. Find it on version/1x branch.

A migration guide is available here.