I am sending data to BLE Device as 20 bytes chunks.
I am receiving back large response.
But onCharacteristicRead
call back, I get only the last piece of the data.
byte[] messageBytes = characteristic.getValue();
if (messageBytes != null && messageBytes.length > 0) {
for(byte byteChar : messageBytes) {
stringBuilder.append((char)byteChar);
}
}
Characteristic's value updates everytime you write to it, that's why when you read, it only reflects the latest value (the last one you write).
To read the data continuously, you should enable the notification on the characteristics first.
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID_DESCRIPTOR);
descriptor.setValue(enabled
? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
: BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
Then you can start writing data
byte[] data = <Your data here>;
BluetoothGattService Service = mBluetoothGatt.getService(UUID_TARGET_SERVICE);
BluetoothGattCharacteristic charac = Service.getCharacteristic(UUID_TARGET_CHARACTERISTIC);
charac.setValue(data);
mBluetoothGatt.writeCharacteristic(charac);
Now everytime you write, the client side will receive a callback of onCharactersticChanged
that contains the newly updated value (data
). You don't need to call the read operation actually.
Remember mBluetoothGatt can only handle 1 operation at a time, if you execute another one while the previous one is unfinished, it won't put in queue, but will return false.