如何在Android中为BLE写出连续快速稳定的特性?

Wun*_*Wun 13 android characteristics bluetooth-lowenergy

我在Android中开发BLE,我可以扫描,连接和写入BLE设备的特性.

我调用下面的函数传递BluetoothGatt,并characteristicAsyncTask当点击Button.

write_btn.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        new WriteCharacteristic(mBluetoothGatt , HueCharacteristic).execute();
     }
});
Run Code Online (Sandbox Code Playgroud)

写特性的代码如下:

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

但我尝试点击该按钮连续,看来Android的没有每次写入characteristicBLE装置.

如果我连续点击按钮5次,则会丢失1~3次.它只能写characteristicBLE装置两次.

题:

Is there any better way to write characteristic consecutive and stable to BLE device for Android?

Dev*_*red 20

Android蓝牙堆栈中的读/写特性系统不擅长排队多个操作.在发送另一个操作之前,您需要等待操作完成.此外,由于您的代码正在使用AsyncTask,您将在某些设备上并行执行任务,因此,当您反复按下按钮时,即使请求也不会被序列化.

要从框架中获得稳定的结果,您需要自己排队这些请求并等待BluetoothGattCallback onCharacteristicWrite()在发送下一个命令之前触发.您的代码需要同步对GATT对象的所有访问,以便下一个writeCharacteristic()永远不会到达完成回调为前一个请求触发.

  • 当我们与多个(2 +)个以上的BLE设备进行通信时,我们是否应该将所有写特征和描述符排队在同一队列中并记录它们应该写入哪个gatt,或者它们可以有单独的队列,所以gatt1.writeCharacteristics(..)和gatt2.writeCharacteristics(..)可能同时写?10Q (2认同)
  • @Devunwired 我和 Ewoks 有同样的问题,你能解释一下吗? (2认同)