我的蓝牙低能耗代码存在问题。我的问题是,有时候oncharacteristicchanged
在2-3 writeCharacteristic
之后没有调用,有时oncharacteristicchanged
调用2-3次(答案相同)
private Queue<BluetoothGattDescriptor> descriptorWriteQueue = new LinkedList<BluetoothGattDescriptor>();
private Queue<BluetoothGattCharacteristic> characteristicWriteQueue = new LinkedList<BluetoothGattCharacteristic>();
这是我的gattcallback:
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
descriptorWriteQueue.remove(); //pop the item that we just finishing writing
if (status == BluetoothGatt.GATT_SUCCESS) {
Logger.E( "Callback: Wrote GATT Descriptor successfully.");
}
else{
Logger.E( "Callback: Error writing GATT Descriptor: " + status);
}
//if there is more to write, do it!
if (descriptorWriteQueue.size() > 0) mBluetoothGatt.writeDescriptor(descriptorWriteQueue.element());
else if (characteristicWriteQueue.size() > 0) mBluetoothGatt.writeCharacteristic(characteristicWriteQueue.element());
}
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
characteristicWriteQueue.remove();
if (status == BluetoothGatt.GATT_SUCCESS) {
//broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
Logger.E("onCharacteristicWrite success: " + status);
}
else{
Logger.E("onCharacteristicWrite error: " + status);
}
//if there is more to write, do it!
if (characteristicWriteQueue.size() > 0) mBluetoothGatt.writeCharacteristic(characteristicWriteQueue.element());
else if (descriptorWriteQueue.size() > 0) mBluetoothGatt.writeDescriptor(descriptorWriteQueue.element());
}
以下是我写作的特点&amp;描述符:
public void writeCharacteristic(BluetoothGattCharacteristic c) {
//put the characteristic into the read queue
characteristicWriteQueue.add(c);
//if there is only 1 item in the queue, then read it. If more than 1, we handle asynchronously in the callback above
//GIVE PRECEDENCE to descriptor writes. They must all finish first.
if ((characteristicWriteQueue.size() == 1) && (descriptorWriteQueue.size() == 0)) {
mBluetoothGatt.writeCharacteristic(c);
}
}
public void writeGattDescriptor(BluetoothGattDescriptor d){
//put the descriptor into the write queue
descriptorWriteQueue.add(d);
//if there is only 1 item in the queue, then write it. If more than 1, we handle asynchronously in the callback above
if ((descriptorWriteQueue.size() == 1) && (characteristicWriteQueue.size() == 0)) {
mBluetoothGatt.writeDescriptor(d);
}
}