Android中BLE如何快速稳定的写入连续的Characteristic?
How to Write consecutive Characteristic fast and stable for BLE in Android?
我正在Android开发BLE,我可以扫描、连接和写入特性到BLE设备。
单击 Button
.
时,我调用以下函数将 BluetoothGatt
和 characteristic
传递给 AsyncTask
write_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new WriteCharacteristic(mBluetoothGatt , HueCharacteristic).execute();
}
});
write characteristic的代码如下:
private class WriteCharacteristic extends AsyncTask<String, Void, String> {
public BluetoothGatt mGatt;
public BluetoothGattCharacteristic mCharacteristic;
public WriteCharacteristic(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic){
mGatt = gatt;
mCharacteristic = characteristic;
}
@Override
protected String doInBackground(String... urls) {
mGatt.writeCharacteristic(mCharacteristic);
return null;
}
}
但我尝试连续点击按钮,似乎Android没有将每个characteristic
写入BLE设备。
连续点击按钮5次,会损失1~3次。它只将 characteristic
写入 BLE 设备 两次。
问题:
Is there any better way to write characteristic consecutive and stable to BLE device for Android?
Android 的蓝牙堆栈中的read/write 特征系统不擅长排队多个操作。在发送另一个操作之前,您需要等待操作完成。此外,由于您的代码使用 AsyncTask
,您将在某些设备上并行执行任务,因此当您重复点击按钮时,即使请求也不会被序列化。
要从框架获得稳定的结果,您需要自己将这些请求排队并等待 BluetoothGattCallback onCharacteristicWrite()
触发,然后再发送下一个命令。您的代码需要同步对 GATT 对象的所有访问,以便下一个 writeCharacteristic()
在前一个请求的完成回调触发之前永远不会出现。
我正在Android开发BLE,我可以扫描、连接和写入特性到BLE设备。
单击 Button
.
BluetoothGatt
和 characteristic
传递给 AsyncTask
write_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new WriteCharacteristic(mBluetoothGatt , HueCharacteristic).execute();
}
});
write characteristic的代码如下:
private class WriteCharacteristic extends AsyncTask<String, Void, String> {
public BluetoothGatt mGatt;
public BluetoothGattCharacteristic mCharacteristic;
public WriteCharacteristic(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic){
mGatt = gatt;
mCharacteristic = characteristic;
}
@Override
protected String doInBackground(String... urls) {
mGatt.writeCharacteristic(mCharacteristic);
return null;
}
}
但我尝试连续点击按钮,似乎Android没有将每个characteristic
写入BLE设备。
连续点击按钮5次,会损失1~3次。它只将 characteristic
写入 BLE 设备 两次。
问题:
Is there any better way to write characteristic consecutive and stable to BLE device for Android?
Android 的蓝牙堆栈中的read/write 特征系统不擅长排队多个操作。在发送另一个操作之前,您需要等待操作完成。此外,由于您的代码使用 AsyncTask
,您将在某些设备上并行执行任务,因此当您重复点击按钮时,即使请求也不会被序列化。
要从框架获得稳定的结果,您需要自己将这些请求排队并等待 BluetoothGattCallback onCharacteristicWrite()
触发,然后再发送下一个命令。您的代码需要同步对 GATT 对象的所有访问,以便下一个 writeCharacteristic()
在前一个请求的完成回调触发之前永远不会出现。