开源软件名称(OpenSource Name):NordicSemiconductor/Android-BLE-Library开源软件地址(OpenSource Url):https://github.com/NordicSemiconductor/Android-BLE-Library开源编程语言(OpenSource Language):Java 95.2%开源软件介绍(OpenSource Introduction):Android BLE LibraryAn Android library that solves a lot of Android's Bluetooth Low Energy problems. ImportingThe library may be found on Maven Central repository. Add it to your project by adding the following dependency: implementation 'no.nordicsemi.android:ble:2.5.1' 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.5.1' To import the BLE library with set of parsers for common Bluetooth SIG characteristics, use: implementation 'no.nordicsemi.android:ble-common:2.5.1' For more information, read this. An extension for easier integration with implementation 'no.nordicsemi.android:ble-livedata:2.5.1' This extension adds Importing as a moduleClone this project and add it to your project:
if (file('../Android-BLE-Library').exists()) {
includeBuild('../Android-BLE-Library')
}
The library uses Java 1.8 features. If you're using Android Studio below 4.2, make sure your build.gradle includes the following configuration: compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
// For Kotlin projects additionally:
kotlinOptions {
jvmTarget = "1.8"
} FeaturesBleManager class provides the following features:
Recent changesVersion 2.4
Version 2.3
When using coroutines, use 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
Version 2.2 breaks some API known from version 2.1.1. Check out migration guide. UsageA class MyBleManager extends BleManager {
private static final String TAG = "MyBleManager";
private BluetoothGattCharacteristic fluxCapacitorControlPoint;
public MyBleManager(@NonNull final Context context) {
super(context);
}
@Override
public int getMinLogPriority() {
// Use to return minimal desired logging priority.
return Log.VERBOSE;
}
@Override
public void log(int priority, @NonNull String message) {
// Log from here.
Log.println(priority, TAG, message);
}
@NonNull
@Override
protected BleManagerGattCallback getGattCallback() {
return new MyGattCallbackImpl();
}
private class MyGattCallbackImpl extends BleManagerGattCallback {
@Override
protected boolean isRequiredServiceSupported(@NonNull BluetoothGatt gatt) {
// Here get instances of your characteristics.
// Return false if a required service has not been discovered.
BluetoothGattService fluxCapacitorService = gatt.getService(FLUX_SERVICE_UUID);
if (fluxCapacitorService != null) {
fluxCapacitorControlPoint = fluxCapacitorService.getCharacteristic(FLUX_CHAR_UUID);
}
return fluxCapacitorControlPoint != null;
}
@Override
protected void initialize() {
// Initialize your device.
// This means e.g. enabling notifications, setting notification callbacks,
// sometimes writing something to some Control Point.
// Kotlin projects should not use suspend methods here, which require a scope.
requestMtu(517)
.enqueue();
}
@Override
protected void onServicesInvalidated() {
// This method is called when the services get invalidated, i.e. when the device
// disconnects.
// References to characteristics should be nullified here.
fluxCapacitorControlPoint = null;
}
}
// Here you may add some high level methods for your device:
public void enableFluxCapacitor() {
// Do the magic.
writeCharacteristic(fluxCapacitorControlPoint, Flux.enable(), BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE)
.enqueue()
}
} The BleManager class exposes high level API for connecting and communicating with Bluetooth LE peripherals. connect(bluetoothDevice)
// Automatic retries are supported, in case of 133 error.
.retry(3 /* times, with */, 100 /* ms interval */)
// A connection timeout can be set. This is additional to the Android's connection timeout which is 30 seconds.
.timeout(15_000 /* ms */)
// The auto connect feature from connectGatt is available as well
.useAutoConnect(true)
// This API can be set on any Android version, but will only be used on devices running Android 8+ with
// support to the selected PHY.
.usePreferredPhy(PhyRequest.PHY_LE_1M_MASK | PhyRequest.PHY_LE_2M_MASK | PhyRequest.PHY_LE_CODED_MASK)
// A connection timeout can be also set. This is additional to the Android's connection timeout which is 30 seconds.
.timeout(15_000 /* ms */)
// Each request has number of callbacks called in different situations:
.before(device -> { /* called when the request is about to be executed */ })
.done(device -> { /* called when the device has connected, has required services and has been initialized */ })
.fail(device, status -> { /* called when the request has failed */ })
.then(device -> { /* called when the request was finished with either success, or a failure */ })
// Each request must be enqueued.
// Kotlin projects can use suspend() or suspendForResult() instead.
// Java projects can also use await() which is blocking.
.enqueue() writeCharacteristic(someCharacteristic, someData, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE)
// Outgoing data can use automatic splitting.
.split(customSplitter, progressCallback /* optional */)
// .split() with no parameters uses the default MTU splitter.
// Kotlin projects can use .splitWithProgressAsFlow(customSplitter) to get the progress as Flow.
.before(device -> { /* called when the request is about to be executed */ })
.with(device, data -> { /* called when the request has been executed */ })
.done(device -> { /* called when the request has completed successfully */ })
.fail(device, status -> { /* called when the request has failed */ })
.invalid({ /* called when the request was invalid, i.e. the target device or given characteristic was null */ })
.then(device -> { /* called when the request was finished with either success, or a failure */ })
// Remember to enqueue each request.
.enqueue() readCharacteristic(someCharacteristic)
// Incoming data can use automatic merging.
.merge(customMerger, progressCallback /* optional */)
// Kotlin projects can use .mergeWithProgressAsFlow(customMerger) to get the progress as Flow.
// Incoming packets can also be filtered, so that not everything goes to the merger.
.filter(dataFilter)
// Complete, merged packets can also be filtered.
.filterPacket(packetFilter)
// [...]
.with(device, data -> { /* called when the data have been received */ })
// [...]
// Once again, remember to enqueue each request!
.enqueue() All requests are automatically enqueued and executed sequentially. GATT Client ExamplePlease refer to the You can run this client on one device and a complimenting server on another (see the next section). GATT Server exampleStarting from version 2.2 you may now define and use the GATT server in the BLE Library. Please refer to the More examplesFind the simple example here Android nRF Blinky. For an example how to use it from a Version 1.xThe 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. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论