I\'m building an app with Android Studio that can read the value from a device BLE. This device, have 4 services. The fourth services have 3 characteristic. I want to read t
First store your read characteristics, and ghatt objects. and if you want to read a value from characteristic call this method:
private fun readDataFromCharacteristic(ghatt: BluetoothGhatt? , characteristic:BluetoothGhattCharacteristic) {
Log.d(TAG, " readDataFromCharacteristic")
ghatt?.readCharacteristic(characteristic)
}
if you call readCharacteristic(characteristic) on ghatt , below method will give result
override fun onCharacteristicRead(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {}
You can achive multiple reads with the following code: First create a List
private int ReadQueueIndex;
private List<BluetoothGattCharacteristic> ReadQueue;
In onServicesDiscovered
add characteristics in ReadQueue:
ReadQueue = new ArrayList<>();
ReadQueue.add(characteristicsList.get(2));
ReadQueue.add(characteristicsList.get(1));
ReadQueue.add(characteristicsList.get(0));
ReadQueueIndex = 2;
ReadCharacteristics(ReadQueueIndex);
Create ReadCharacteristics
method
private void ReadCharacteristics(int index){
bluetoothGatt.readCharacteristic(ReadQueue.get(index));
}
Then in your onCharacteristicRead
callback:
String value = Arrays.toString(characteristic.getValue());
if(characteristic.getUuid().equals(characteristicsList.get(0).getUuid())){
Log.i("Characteristic 0:", value);
} else if(characteristic.getUuid().equals(characteristicsList.get(1).getUuid())){
Log.i("Characteristic 1:", value);
} else if(characteristic.getUuid().equals(characteristicsList.get(2).getUuid())){
Log.i("Characteristic 2:", value);
}
ReadQueue.remove(ReadQueue.get(ReadQueueIndex));
if (ReadQueue.size() >= 0) {
ReadQueueIndex--;
if (ReadQueueIndex == -1) {
Log.i("Read Queue: ", "Complete");
}
else {
ReadCharacteristics(ReadQueueIndex);
}
}
Hope its helpful.
You should not read whole list of characteristics in onServicesDiscovered method, because ble device could havent a time to performs all requests from android client.
I offer you: