How could I achieve maximum thread safety with a read/write BLE Gatt Characteristic?

后端 未结 2 1162

I am communicating with a BLE device that sends me lots of data via one characteristic. The same Characteristic is used to send data to the device.

Inside Androids

2条回答
  •  梦毁少年i
    2020-12-20 14:33

    In SDK27, the onNotify() callback function in BluetoothGatt.java was updated to call BOTH BluetoothGattCharacteristic.setValue() and BluetoothGattCallback.onCharacteristicChanged() in the Runnable's run().

    This change allows us to force all calls to BluetoothGattCharacteristic.setValue() - both for our outbound writing to the characteristic and the inbound notifications - onto the same thread, which eliminates the race condition corrupting the BluetoothGattCharacteristic.mValue;

    1. Create a HandlerThread
    2. Create a Handler attached to your HandlerThread
    3. Pass your Handler into BluetoothDevice.connectGatt() - congratulations, when a notify is received the setValue() and onCharacteristicChanged() will be called on your HandlerThread.
    4. When you want to write to the characteristic, post your setValue() and writeCharacteristic() to your HandlerThread via your Handler

    Now all the function calls that were involved in the race condition are being executed on the same thread, eliminating the race condition.

提交回复
热议问题