如何在Android中为BLE快速稳定地编写连续特征? [英] How to Write consecutive Characteristic fast and stable for BLE in Android?
问题描述
我正在Android中开发BLE,我可以扫描,连接特征并将其写入BLE设备.
I am developing BLE in Android , I can scan, connected and write characteristic to to the BLE device.
单击Button
时,我调用以下函数将BluetoothGatt
和characteristic
传递给AsyncTask
.
I call the following function to pass BluetoothGatt
and characteristic
to AsyncTask
when click the Button
.
write_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new WriteCharacteristic(mBluetoothGatt , HueCharacteristic).execute();
}
});
写特征码如下:
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设备.
But I try to click the button consecutive, it seems the Android did not write every characteristic
to the BLE device.
如果我连续单击该按钮5次,它将丢失1〜3次.只会将characteristic
写入 BLE设备两次.
If I click the button consecutive for 5 times , it will loss 1~3 times. It only write characteristic
to BLE device for two times.
问题:
Is there any better way to write characteristic consecutive and stable to BLE device for Android?
Is there any better way to write characteristic consecutive and stable to BLE device for Android?
推荐答案
Android蓝牙堆栈中的读/写特征系统不能很好地排队多个操作.您需要先等待操作完成,然后再进行发送.另外,由于您的代码使用AsyncTask
,因此您将在某些设备上并行执行任务,因此当您反复按下按钮时,甚至请求也不会被序列化.
The read/write characteristic system in Android's Bluetooth stack isn't good at queueing up multiple operations. You need to wait for operations to complete before sending along another one. In addition, since your code is using AsyncTask
, you will get parallel execution of tasks on some devices, so even the requests aren't being serialized when you repeatedly hit the button.
要从框架中获得稳定的结果,您需要自己将这些请求排队,然后等待
To get stable results from the framework, you will need to queue up those requests yourself and wait for BluetoothGattCallback onCharacteristicWrite()
to trigger before sending the next command. Your code needs to synchronize all access to the GATT object, so that the next writeCharacteristic()
never comes until the completion callback fires for the previous request.
这篇关于如何在Android中为BLE快速稳定地编写连续特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!