BxAndroidBle 无法读取设备,状态 = 22



我在读取 Ble 设备和使用 RxAndroidBle 库时遇到问题。

我不断收到此错误:

BleGattException{status=22, bleGattOperation=BleGattOperation{description='CONNECTION_STATE'}}

任何人都可以查看我的代码并了解我可能做错了什么:

subscription = rxBleDevice.establishConnection(context, true)
            .subscribe(rxBleConnection -> {
                rxBleConnection.readCharacteristic(UUID.fromString(UUID_LOG_COUNT)).doOnNext(Action1 -> Logger.d(Helper_Utils.reverseHex(HexString.bytesToHex(Action1))));
            }, throwable -> {
                Logger.d("Error", throwable.getMessage());
            });

如果您需要更多信息,我会尽力提供。

编辑

我用过2部不同的手机:一加二安卓6.0.1摩托G玩安卓6.0.1

我已经尝试多次打开和关闭wifi和蓝牙。我从来没有能够阅读这个例子。

>status = 22是与Android操作系统断开外围设备连接有关的问题。您可以从代码中无能为力来防止它。

至于不读取特征值 - 那是因为你没有订阅它。RxJava编程(或一般的反应式编程(的最佳方法是准备一个只有一个订阅的流,因为这样可以最大限度地减少状态量。

你可以这样做:

Subscription s = rxBleDevice.establishConnection(true) // establish the connection
  .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(UUID.fromString(UUID_LOG_COUNT))) // when the connection is established start reading the characteristic
  .take(1) // after the first value unsubscribe from the upstream to close the connection
  .subscribe( // subscribe to read values
    characteristicValue -> Logger.d(Helper_Utils.reverseHex(HexString.bytesToHex(characteristicValue))), // do your thing with the read value here
    throwable -> Logger.d("Error", throwable.getMessage()) // log / show possible error here
  );

请记住,.subscribe()的结果是一个Subscription,您可以通过调用Subscription.unsubscribe()来取消该这将断开外围设备的连接。

我的代码引用了昨天发布的RxAndroidBle 1.2.0引入的新API。

谢谢s_noopy找到我的问题。

这是我问题的解决方案:

subscription = rxBleDevice.establishConnection(context, true)
        .subscribe(rxBleConnection -> {
           rxBleConnection.readCharacteristic(UUID.fromString(UUID_LOG_COUNT))
.subscribe(characteristicValue -> {
                            Logger.d(Helper_Utils.reverseHex(HexString.bytesToHex(characteristicValue)));
                        });
        }, throwable -> {
            Logger.d("Error", throwable.getMessage());
        });

我用 .subscribe 更改了 .doOnNext

最新更新