Android BLE readCharacteristic 失败

标签 android bluetooth-lowenergy android-ble

当我连接到 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 操作创建一个命令队列,并一次运行一个。您可以使用命令模式来完成此操作。

关于Android BLE readCharacteristic 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30398599/

相关文章:

notifications - Android Ble 延迟通知

arduino - BLE Arduino ESP32 - 我应该使用哪个库?

Android ble 设备有时不会断开连接

android - RxAndroidBle - 如何断开所有连接的设备?

android - 包裹中 `createTypedArrayList()`和 `readTypedList()`的区别

android - 当用户离线时,Firebase Auth session 会持续多长时间?

java - 无法将我的 android 应用程序中的 facebook 发布到给定的 postId

android - 使用正则表达式解析 HLS m3u8 文件

android - 为什么 isMultipleAdvertisementSupported() 在 getBluetoothLeAdvertiser 返回对象时返回 false?

android - 如何格式化要发送到 BLE 设备上的特征的字节数组?