如何使用rxandroidble禁用通知?

时间:2016-11-08 11:07:13

标签: 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不是最适合高吞吐量的技术,但它在这里用于R& D目的:))

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

只要订阅来自Observable的{​​{1}},就会启用通知。要禁用通知,必须取消订阅上述订阅。

有几种方法可以编码。其中之一是:

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>

答案 1 :(得分:0)

科特琳

在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()