Android BLE readCharacteristic 失败

Android BLE readCharacteristic fails

我试图在连接到 BLE 设备时读取它的初始状态。这是我必须尝试执行的代码:

@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status)
{
    if(status == BluetoothGatt.GATT_SUCCESS)
    {
        Log.i(TAG, gatt.getDevice().toString() + "Discovered Service Status: " + gattStatusToString(status));
        for(BluetoothGattService service : gatt.getServices())
        {
            Log.i(TAG, "Discovered Service: " + service.getUuid().toString() + " with " + "characteristics:");
            for(BluetoothGattCharacteristic characteristic : service.getCharacteristics())
            {
                // Set notifiable
                if(!gatt.setCharacteristicNotification(characteristic, true))
                {
                    Log.e(TAG, "Failed to set notification for: " + characteristic.toString());
                }

                // Enable notification descriptor
                BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CCC_UUID);
                if(descriptor != null)
                {
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    gatt.writeDescriptor(descriptor);
                }

                // Read characteristic
                if(!gatt.readCharacteristic(characteristic))
                {
                    Log.e(TAG, "Failed to read characteristic: " + characteristic.toString());
                }
            }
        }
    }
    else
    {
        Log.d(TAG, "Discover Services status: " + gattStatusToString(status));
    }
}

但是每次读取都失败!稍后,如果我根据 UI 交互启动读取,它读取起来就很好了!对这里发生的事情有什么想法吗?

在Android BLE 实现中,gatt 操作调用需要排队,以便一次只有一个操作(读、写等)有效。所以比如调用gatt.readCharacteristic(characteristicX)后,需要等待gatt回调BluetoothGattCallback.onCharacteristicRead()表示读取完成。如果在前一个操作完成之前启动第二个 gatt.readCharacteristic() 操作,则第二个操作将失败(返回 false)这适用于所有 gatt.XXX() 操作。

这有点麻烦,但我认为最好的解决方案是为所有 gatt 操作创建一个命令队列,并且 运行 一次创建一个。您可以使用命令模式来完成此操作。