使用 Gatt 与 BLE 设备通信时,我不太明白。 根据这个: https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback)
BluetoothGatt gatt = device.connectGatt(context,true,new BluetoothGattCallback(){....})
我可以连接到 BLE 设备并给它一个回调对象,以便在诸如 onCharacteristicRead 和 onCharacteristicWrite 之类的事情上得到通知
我不明白的是,哪个写入对应于哪个读取回调?
这个方法签名是:
public void onCharacteristicRead (BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
public void onCharacteristicWrite (BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
所以如果我这样做:
BluetoothGattCharacteristic char = gatt.getService(UART_SERVICE_UUID).getCharacteristic(UART_TX_CHARACTERISTIC_UUID);
char1.setValue("command1");
gatt.writeCharacteristic(char);
char1.setValue("command2");
gatt.writeCharacteristic(char);
在 onCharacteristicRead 回调中,我如何知道 characteristic.getStringValue() 是针对 command1 还是 command2?
谢谢!
最佳答案
在使用 BluetoothGatt.writeCharacteristic()
和相关的 BluetoothGatt
方法时,有几件重要的事情需要了解。
请注意
writeCharacteristic()
(以及BluetoothGatt
的许多其他方法)返回一个 bool 值。当结果为 false 时,表示操作没有成功启动。那是什么时候发生的?请参阅下一项。使用
BluetoothGatt
对象,不可能同时启动两个操作。启动第二个的调用将失败并返回 false。调用writeCharacteristic()
后,代码必须等待回调响应 (onCharacteristicWrite
) 才能发出另一次写入。由于这个原因,在这个问题的示例代码中,第二次调用writeCharacteristic()
几乎肯定会返回 false。
通过这种方式,如果每个 BluetoothGatt 操作都等待对先前发出的命令的回调,您就可以成功地将命令启动和回调配对——真的是被迫的。
关于Android Bluetooth Low Energy 获取对特定请求的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31025090/