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 BluetoothGattCharacteristic
there are the methods
public byte[] getValue() {
return mValue;
}
public boolean setValue(byte[] value) {
mValue = value;
return true;
}
However, the execution happens from different threads. Android runs about 5 different binder-threads and they call
onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic)
I now try to grab the array as first operation in the callback, but it is NOT guaranteed that another thread (not under my control) is setting the array at the same time.
While above seems to do the trick, a more complicated matter is sending data 'against an incoming stream of data'.
I have to use the same Characteristic to send data down to the device, so I setValue()
and then BluetoothGatt.writeCharacteristic
.
public boolean writeCharacteristic(BluetoothGattCharacteristic characteristic) {
// some null checks etc
//now it locks the device
synchronized(mDeviceBusy) {
if (mDeviceBusy) return false;
mDeviceBusy = true;
}
//the actual execution
return true;
}
I will then at some point receive a callback from some thread
onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
However, when I grab the value and try to check if it is what I wanted to send, sometimes it already is a received package that has just been updated from some other thread.
How could i make this more thread-safe without having access to Androids BLE API or the stack etc ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…