在我的应用程序中,我获得了READ 和WRITE 以处理特定的BluetoothGattCharacteristic
对象。
BluetoothGattCallback
onCharacteristicWrite
和 onCharacteristicRead
被正确调用。
然后我尝试设置 NOTIFY 选项,以便在设备上的特定特征发生变化时通知我的 Android 应用程序。
我已通过以下代码进行设置:
// Local notifications
mGatt.setCharacteristicNotification(statusTypeCharacteristic, notify);
// Remote notifications
BluetoothGattDescriptor desc = statusTypeCharacteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
Log.d("Descriptor", desc.toString());
boolean test;
test = desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); // return value = true
test = mGatt.writeDescriptor(desc); // return value = true
当特性发生变化时,回调:onCharacteristicChanged
正在按预期调用
但是,现在所有的READ 和WRITE 操作都不再有效了。 当我评论处理描述符的行时,READ 和 WRITE 再次起作用。
我非常不清楚的部分是用于获取描述符的 UUID
。这是正确的吗?我是否应该扫描特征中的所有描述符并在其中一个上启用通知?当我有多个返回时,我怎么知道要设置哪一个?
最佳答案
好的,所以我已经弄清楚了这个问题。 在我的应用程序开始时,我正在配置(即写入)许多描述符。 2个问题: 1- 一次只能写入一个描述符 2- 写入描述符时不会发生读/写操作
解决方法是创建一个写入描述符操作队列,并在 onDescriptorWrite 回调中执行下一个描述符写入。
private 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
if(descriptorWriteQueue.size() == 1) {
mGatt.writeDescriptor(d);
}
}
然后在回调中:
@Override
public void onDescriptorWrite (BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
// Called when the descriptor is updated for notification
Log.d("onDescriptorWrite", descriptor.getUuid().toString());
// pop the item that we just finishing writing
descriptorWriteQueue.remove();
// if there is more to write, do it!
if(descriptorWriteQueue.size() > 0) {
mGatt.writeDescriptor(descriptorWriteQueue.element());
}
// Inform the framework that the scope has connected, configured and ready to process commands
if(descriptorWriteQueue.size() == 0) {
// Do something else, such as reads and writes
}
}
关于android - 使 READ、WRITE 和 NOTIFY 在 Android BLE(版本 21 及更高版本)上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37082059/