Android Bluetooth Low Energy 获取对特定请求的响应

标签 android bluetooth bluetooth-lowenergy gatt

使用 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 方法时,有几件重要的事情需要了解。

  1. 请注意 writeCharacteristic()(以及 BluetoothGatt 的许多其他方法)返回一个 bool 值。当结果为 false 时,表示操作没有成功启动。那是什么时候发生的?请参阅下一项。

  2. 使用BluetoothGatt 对象,不可能同时启动两个操作。启动第二个的调用将失败并返回 false。调用 writeCharacteristic() 后,代码必须等待回调响应 (onCharacteristicWrite) 才能发出另一次写入。由于这个原因,在这个问题的示例代码中,第二次调用 writeCharacteristic() 几乎肯定会返回 false。

通过这种方式,如果每个 BluetoothGatt 操作都等待对先前发出的命令的回调,您就可以成功地将命令启动和回调配对——真的是被迫的。

关于Android Bluetooth Low Energy 获取对特定请求的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31025090/

相关文章:

android - 蓝牙设备的循环问题

android - 蓝牙查找设备落下程序

java - 蓝牙回调函数 onCharacteristicRead 没有对使用 <API 21 的另一个 Activity 进行 Intent 调用。不在 Marshmallow 中

ios - 如何在 iOS 应用程序终止时继续扫描 BLE 传感器并识别传感器 keyEvent

android - 联系信标 : Inconsistent and unreliable results when determining beacon distance

android - 连接充电器时在 Android 上自动开机

java - 我如何组织和减少申请中的类(class)数量

java - android studio中有 "java.io.IOException"问题的解决方案吗?

android - 将 ListView 中的选择从橙色更改为绿色

java - BLE设备与同一设备上不同Android应用程序之间的通信