【问题标题】:Cancelling BluetoothGatt read/write operation?取消 BluetoothGatt 读/写操作?
【发布时间】:2017-05-22 14:37:59
【问题描述】:
我是在 Android 上进行 BLE 开发的新手,我正在查看 API 文档,但没有看到取消已“排队”到远程设备的读/写特征/描述符操作的方法。我怎样才能做到这一点?
具体来说,在调用以下之后,如何在超时后取消写入(使用 AsyncTask 在其他地方处理)?
private void writeCharacteristic(BluetoothGatt gatt) {
Log.i(TAG, "Writing to " + mCharacteristic);
characteristic.setValue(mPayload);
gatt.writeCharacteristic(mCharacteristic);
}
【问题讨论】:
标签:
android
bluetooth
bluetooth-lowenergy
【解决方案1】:
你不能。一个写请求被发送到远程设备,它用一个写响应来回答。当收到写入响应时,会调用 onCharacteristicWrite 回调。 BLE 协议中没有指定“取消”。而是指定了 30 秒超时。如果远程设备在 30 秒内未发送写入响应,则链接将断开。这是在 Android 的蓝牙堆栈中为您实现的。由于 GATT 协议一次也可能只有一个未完成的请求,因此无法“重试”该操作。
【解决方案2】:
我建议不要以这种方式处理操作,因为不能保证任何蓝牙 LE 操作会在 X 时间内成功或失败。距离、干扰等因素都会影响您的操作。
您将在 BluetoothGattCallback 方法上获得明确的操作结果。例如:
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
if (status==BluetoothGatt.SUCCESS)
{
//operation completed successfully
}
else
{
//operation failed
}
}
特征和描述符的所有写入/读取操作都会提供类似的结果。