Android BLE readCharacteristic失败

Cas*_*eyB 5 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));
    }
}
Run Code Online (Sandbox Code Playgroud)

但每次读取失败!稍后,如果我基于UI交互启动读取,它就读得很好!关于这里发生了什么的任何想法?

Rob*_*man 15

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

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

  • 不可以.通知特征没有命令/响应模式.通知(onCharacteristicChanged)以异步方式进入,不应影响或不受其他读写命令排队的影响. (3认同)