首页 > 解决方案 > 顺序的等待语句

问题描述

我有一个问题导致需要从一件事到另一件事依次等待。我目前通过设置 3 个具有不同延迟的可运行对象来做到这一点,以允许数据的顺序流出现在我的蓝牙连接上。然而,虽然这确实有效,但我觉得必须有一个更好/更清洁的实现。我现在的代码如下。

我的代码是这样工作的:

请您就如何以更好的方式一个接一个地执行我的写入功能给我一些建议。

Handler h =new Handler() ;
h.postDelayed(new Runnable() {
    public void run() {
        Log.d(TAG, "Write 1");
        mBluetoothLeService.writeCharacteristic(10);
    }
}, 1000);

Handler h1 =new Handler() ;
final int Command_to_run = value;
h1.postDelayed(new Runnable() {
    public void run() {
        Log.d(TAG, "Write 2");
        mBluetoothLeService.writeCharacteristic(Command_to_run);
    }
}, 2000);

Handler h2 =new Handler() ;
h2.postDelayed(new Runnable() {
    public void run() {
        Log.d(TAG, "Write 3");
        mBluetoothLeService.writeCharacteristic(20);
    }
}, 3000);

编写代码

 public void writeCharacteristic(int Data) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }

        byte[] value = intToByteArray(Data);

        BluetoothGattService mCustomService = 
        mBluetoothGatt.getService(UUID.fromString("f3641400-00b0-4240-ba50- 
        05ca45bf8abc"));
        if(mCustomService == null){
            Log.w(TAG, "Custom BLE Service not found");
            return;
        }
        /*get the read characteristic from the service*/
        BluetoothGattCharacteristic characteristic = 
        mCustomService.getCharacteristic(UUID.fromString("f3641401-00b0-4240- 
        ba50-05ca45bf8abc"));
        characteristic.setValue(value);
        mBluetoothGatt.writeCharacteristic(characteristic);
    }

标签: javaandroidbluetooth-lowenergydelaywait

解决方案


Android 的 BLE API 是完全异步的,没有阻塞方法。如果操作成功启动,这些方法将返回 true,否则返回 false。特别是,如果已经有操作正在进行,则将返回 false。

当您调用requestMtu, writeCharacteristic,等时,操作完成时将调用readCharacteristic相应的回调onMtuChanged, 。请注意,这通常意味着到远程设备的往返,这可能需要不同的时间来完成,具体取决于环境的嘈杂程度以及您拥有的连接参数,因此睡眠或延迟一些固定数量的时间永远不是一个好主意时间并假设操作已经完成。onCharacteristicWriteonCharacteristicRead

为了使代码结构更好一点并避免“回调地狱”,您可以例如实现一个(线程安全的)GATT 队列,稍后由您的应用程序使用。这样你就可以在队列中推送你想要的东西,让你的 GATT 队列库处理脏东西。或者您可以使用一些已经执行此操作的 Android BLE 库。

有关更彻底的讨论,请参阅https://medium.com/@martijn.van.welie/making-android-ble-work-part-3-117d3a8aee23 。


推荐阅读