Master Crouch Master Crouch - 3 years ago 138
Android Question

Android BLE: Successfully write ENABLE_NOTIFICATION_VALUE value to BluetoothGattDescriptor but onCharacteristicChanged never fires

I have a BLE peripheral that works fine with a given Service / Characteristic UUID on iOS and Android 7.0. On Android 6.0 Marshmallow the onCharacteristicChanged method will not fire despite setting the ENABLE_NOTIFICATION_VALUE on the descriptor. Please help me figure out how to get the onCharacteristicChanged to fire for an Android device running Android OS 6.0 Marshmallow. Here is the code I am using to try to get notifications to work:

boolean success = mBluetoothGatt.setCharacteristicNotification(characteristic, true);
Log.e(TAG, "set char notification = " + (success ? "It worked :)" : "It did not work :("));

if (UUID_DATA_PACKET.equals(characteristic.getUuid())) {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(EkoCoreGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));

descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

success = mBluetoothGatt.writeDescriptor(descriptor);
Log.e(TAG, "set descriptor = " + descriptor.getCharacteristic().getWriteType() + ", success = " + (success ? "It worked :)" : "It did not work :("));
}


In the code above both the setCharacteristicNotification and writeDescriptor calls return success (1 / true / etc). Additionally the onDescriptorWrite callback returns GATT_SUCCESS. However, when we read the descriptor at a later point in the code it is found that the notification value is still set to disabled. We have tried many solutions such as putting a delay between the setCharacteristicNotification and writeDescriptor calls but haven't found a solution to this issue. Pairing with the peripheral in question is no problem, but getting the notifications seems somehow impossible. Any tips would be appreciated.

Answer Source

Adding the following before writing the descriptor fixed my issue:

characteristic.setWriteType(BluetoothGattCharacteristic.WRIT‌​E_TYPE_DEFAULT);

Clearly there is some bug in Android 6. I hope this answer helps someone else. It was quite the headache to find.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download