Android BLE readCharacteristic fails

I am trying to read the initial state of a BLE device when I connect to it. Here is the code I should try to do:

@Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { if(status == BluetoothGatt.GATT_SUCCESS) { Log.i(TAG, gatt.getDevice().toString() + "Discovered Service Status: " + gattStatusToString(status)); for(BluetoothGattService service : gatt.getServices()) { Log.i(TAG, "Discovered Service: " + service.getUuid().toString() + " with " + "characteristics:"); for(BluetoothGattCharacteristic characteristic : service.getCharacteristics()) { // Set notifiable if(!gatt.setCharacteristicNotification(characteristic, true)) { Log.e(TAG, "Failed to set notification for: " + characteristic.toString()); } // Enable notification descriptor BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CCC_UUID); if(descriptor != null) { descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); gatt.writeDescriptor(descriptor); } // Read characteristic if(!gatt.readCharacteristic(characteristic)) { Log.e(TAG, "Failed to read characteristic: " + characteristic.toString()); } } } } else { Log.d(TAG, "Discover Services status: " + gattStatusToString(status)); } } 

But reading fails every time! Later, if I start reading based on interaction with the user interface, it reads just fine! Any ideas on what's going on here?

+5
source share
1 answer

In an Android BLE implementation, calls to the gatt operation must be queued to only have one operation at a time (read, write, etc.). So, for example, after calling gatt.readCharacteristic(characteristicX) you need to wait for the answer to the gatt call BluetoothGattCallback.onCharacteristicRead() to show that the reading is complete. If you initiate the second operation gatt.readCharacteristic () before the previous one completes, the second will fail (returning false). This applies to all gatt.XXX () operations.

This is a little work, but I think the best solution is to create a command queue for all gatt operations and run them one at a time. You can use the command template to accomplish this.

+12
source

All Articles