如何使用 rxandroidble 禁用通知?

How to disable a notification with 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 不是最适合高吞吐量的技术,但它是用于研发目的:))

感谢您的帮助!

只要来自 RxBleConnection.setupNotification()Observable 被订阅,就会启用通知。要禁用通知,必须取消订阅上述订阅。

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

    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

科特林

在 kotlin 中,使用 dispose() 禁用通知。

#ENABLE NOTIFICATION
val result = device.establishConnection(false)
.flatMap(rxBleConnection -> rxBleConnection.setupNotification(characteristicUuid))
.doOnNext(notificationObservable -> {
    // Notification has been set up
})
.flatMap(notificationObservable -> notificationObservable) // <-- Notification has been set up, now observe value changes.
.subscribe(
    bytes -> {
        // Given characteristic has been changes, here is the value.
    },
    throwable -> {
        // Handle an error here.
    }
);


#DISABLE NOTIFICATION
result.dispose()

尝试取消订阅但没有成功,仍然不确定哪个是最好的 dispose() 或 unsubscribe()