我目前正在尝试使用 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/