Well, first of all, I strongly recommend that you use the amazing Bluetooth LE open-source library called RxAndroidBle. It will make the whole process way easier.
Once you have included that library in your project, you will want to do the following:
- Make sure that the Bluetooth is enabled and that you have already asked the user for Location permissions.
- Scan for devices
Example:
RxBleClient rxBleClient = RxBleClient.create(context);
Disposable scanSubscription = rxBleClient.scanBleDevices(
new ScanSettings.Builder()
// .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) // change if needed
// .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) // change if needed
.build()
// add filters if needed
)
.subscribe(
scanResult -> {
// Process scan result here.
},
throwable -> {
// Handle an error here.
}
);
// When done, just dispose.
scanSubscription.dispose();
- Connect to the desired device and use the
writeCharacteristic()
method to write the bytes you want.
Example:
device.establishConnection(false)
.flatMapSingle(rxBleConnection -> rxBleConnection.writeCharacteristic(characteristicUUID, bytesToWrite))
.subscribe(
characteristicValue -> {
// Characteristic value confirmed.
},
throwable -> {
// Handle an error here.
}
);
- If instead, you want to set up the notification/indication on a characteristic, you can do the following:
Example:
device.establishConnection(false)
.flatMap(rxBleConnection -> rxBleConnection.setupNotification(characteristicUuid))
.doOnNext(notificationObservable -> {
// Notification has been set up
})
.flatMap(notificationObservable -> notificationObservable) // <-- Notification has been set up, now observe value changes.
.subscribe(
bytes -> {
// Given characteristic has been changes, here is the value.
},
throwable -> {
// Handle an error here.
}
);
There is plenty of information in their Github page and also they have their own dedicated tag in Stackoverflow.