android - 如何使用 rxandroidble 禁用通知?

标签 android android-bluetooth android-ble rxandroidble

我目前正在尝试使用 rxandroidble 来替换我们其中一款应用的 Android 原生 BLE API。

如何禁用通知?我可以使用示例代码启用它,这个:

device.establishConnection(context, false)
.flatMap(rxBleConnection -> rxBleConnection.setupNotification(characteristicUuid)) 
.doOnNext(notificationObservable -> { // OK }) 
.flatMap(notificationObservable -> notificationObservable)     
.subscribe(bytes -> { // OK });

但在我的产品中,我有一个用例,我必须按需禁用/启用通知。

另外,我尝试直接取消订阅/重新连接而不是禁用/启用通知,但显然从未执行过取消订阅命令,我的假设是因为我的吞吐量很高(我的设备以 300 - 400Hz 的频率通知),这是否合理?

(我知道 BLE 不是最适合高吞吐量的技术,但它是用于研发目的:))

感谢您的帮助!

最佳答案

每当 Observable 时启用通知来自 RxBleConnection.setupNotification()将被订阅。要禁用通知,必须取消订阅上述订阅。

有几种编码方式。其中之一是:

    final RxBleDevice rxBleDevice = // your RxBleDevice
    final Observable<RxBleConnection> sharedConnectionObservable = rxBleDevice.establishConnection(this, false).share();

    final Observable<Boolean> firstNotificationStateObservable = // an observable that will emit true when notification should be enabled and false when disabled
    final UUID firstNotificationUuid = // first of the needed UUIDs to enable / disable
    final Subscription subscription = firstNotificationStateObservable
            .distinctUntilChanged() // to be sure that we won't get more than one enable commands
            .filter(enabled -> enabled) // whenever it will emit true
            .flatMap(enabled -> sharedConnectionObservable // we take the shared connection
                    .flatMap(rxBleConnection -> rxBleConnection.setupNotification(firstNotificationUuid)) // enable the notification
                    .flatMap(notificationObservable -> notificationObservable) // and take the bytes
                    .takeUntil(firstNotificationStateObservable.filter(enabled1 -> !enabled1)) // and we are subscribing to this Observable until we want to disable - note that only the observable from sharedConnectionObservable will be unsubscribed
            )
            .subscribe(
                    notificationBytes -> { /* handle the bytes */ },
                    throwable -> { /* handle exception */ }
            );

请注意,在上面的示例中,连接将在最后一次订阅 sharedConnectionObservable 时关闭。将结束。

要启用/禁用不同的特性,您可以复制并粘贴上面的代码以不同的 Observable<Boolean>作为启用/禁用输入和不同的 UUID的。

关于android - 如何使用 rxandroidble 禁用通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40485301/

相关文章:

安卓应用 : Connecting to GATT server using UUIDs

android - ScanCallback onBatchScanResults 被无限期调用

java - 我无法使用 fragment 从我的 Activity 访问 fragment 布局内的 TextView

android - 拦截 PopupWindow 中的 Android 菜单按钮

java - 我应该从 getFft 看到什么样的输出?

java - 如何使用jsoup在android中发送POST?

android - 如何以编程方式判断蓝牙设备是否已连接?

android - API 21 中弃用了 startLeScan

Android BluetoothGatt 未收到特征通知 BluetoothGatt#writeDescriptor(desc) 返回 false

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