RxAndroidBLE 的使用

作者: linheimx | 来源:发表于2016-08-23 20:07 被阅读3246次
picpic

GitHub

RxAndroidBLE

介绍

开发Android的BLE很痛苦,RxAndroidBLE可以极大的减轻您这方面的苦恼(手动滑稽)。
它依赖于RxJava,将 BLE 相关的复杂的Api转变为 可交互性的observables
它为你提供了以下特色:

  1. 漂亮的异步操作支持(读,写,通知)
  2. Android下的线程管理(主线程,后台线程。。。)。
  3. 连接与操作的失败处理。

使用

a. 获得 client

你需要维护一个client的单例:

RxBleClient rxBleClient = RxBleClient.create(context);

b. 发现设备

在一定的区域内扫描设备:

Subscription scanSubscription = rxBleClient.scanBleDevices()
    .subscribe(rxBleScanResult -> {
        // Process scan result here.
    });


// When done, just unsubscribe.(扫描设备 结束后,取消订阅)
scanSubscription.unsubscribe();

c. 连接

连接完成后,才能进行读写操作。所以连接是必须的:

String macAddress = "AA:BB:CC:DD:EE:FF";
RxBleDevice device = rxBleClient.getBleDevice(macAddress);

Subscription subscription = device.establishConnection(context, false) // <-- autoConnect flag(自动连接的标志)
    .subscribe(rxBleConnection -> {
        // All GATT operations are done through the rxBleConnection.
    });

// When done... unsubscribe and forget about connection teardown :)
subscription.unsubscribe();

说一下 自动连接

  1. 官网:
    [https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#connectGatt(android.content.Context](https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#connectGatt(android.content.Context), boolean, android.bluetooth.BluetoothGattCallback):
    autoConnect boolean: Whether to directly connect to the remote device (false) or to automatically connect as soon as the remote device becomes available (true).
    (直接连接:false,自动连接:true---》只要远处设备可见(可用)就自动连接上设备)

  2. 作者说:
    自动连接这个概念,第一眼看上去,让人充满了误解。
    设置 autoconnect flag 为false:若外围蓝牙设备不再广播,RxBleDevice#establishConnection 方法会被调用,一个error将被提交。这个时间大概在10s左右。
    设置 autoconnect flag 为true:允许你等待,直到 ble的设备被发现可用。直到连接成功以后,RxBleConnection的实例才会提交。它也持有了 wake 锁,等到连接被建立了以后,android的设备也将会被唤醒。但这个特色在将来也许会变。
    (原文:From experience it also handles acquiring wake locks, so it's safe to assume that your Android device will be woken up after the connection has been established - but it is not a documented feature and may change in the future system releases.)

  3. 注意:不要过度使用 自动连接,这是有负面影响的:初始连接的速度很慢。原因:因为优化的原因,后台的扫描间隔比较慢,所以它要花费更多的时间去建立连接。
    (原文:Scanning window and interval is lowered as it is optimized for background use and depending on Bluetooth parameters it may (and usually do) take more time to establish the connection.)

d. 读写操作

device.establishConnection(context, false)
    .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(characteristicUUID))
    .subscribe(characteristicValue -> {
        // Read characteristic value.
    });
device.establishConnection(context, false)
    .flatMap(rxBleConnection -> rxBleConnection.writeCharacteristic(characteristicUUID, bytesToWrite))
    .subscribe(characteristicValue -> {
        // Characteristic value confirmed.
    });
  1. 多个 读
 device.establishConnection(context, false)
    .flatMap(rxBleConnection -> Observable.combineLatest(
        rxBleConnection.readCharacteristic(firstUUID),
        rxBleConnection.readCharacteristic(secondUUID),
        YourModelCombiningTwoValues::new
    ))
    .subscribe(model -> {
        // Process your model.
    });
  1. 读写结合
 device.establishConnection(context, false)
    .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(characteristicUuid)
        .doOnNext(bytes -> {
            // Process read data.
        })
        .flatMap(bytes -> rxBleConnection.writeCharacteristic(characteristicUuid, bytesToWrite)))
    .subscribe(writeBytes -> {
        // Written data.
    });

e. 改变通知

device.establishConnection(context, 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.
    });

f. 观察连接状态

当你想观察设备的连接状态,做如下订阅:

device.observeConnectionStateChanges()
    .subscribe(connectionState -> {
        // Process your way.
    });

g. 日志

为了连接调试,你可以使用拓展的日志:

RxBleClient.setLogLevel(RxBleLog.DEBUG);

l. 错误处理

当你遇到错误的时候,你会得到 onError 这个callback,每个公共的方法上有JavaDoc 来解释可能存在的错误。

相关文章

  • RxAndroidBLE 的使用

    GitHub RxAndroidBLE 介绍 开发Android的BLE很痛苦,RxAndroidBLE可以极大的...

  • RxAndroidBle

    介绍 RxAndroidBle Android是一个针对的蓝牙低功耗问题的一剂良药。由RxJava支持,通过观察者...

  • 引入RxAndroidBle报错引发的问题

    在项目中引入RxAndroidBle的第一步就碰到了问题,Build后直接报错 从以上log中根本看不到什么有用的...

  • RxAndroidBLE 源码分析:扫描蓝牙设备

    ![Uploading Paste_Image_636799.png . . .]](http://upload-...

  • RxAndroidBLE 源码分析:建立蓝牙连接

    1. 得到 外围蓝牙设备 想与 外围的蓝牙设备相连接,首先得要获得这个蓝牙设备。 官方例子: 具体的实现:由 Rx...

  • iconfont的使用(下载使用)

    1、下载文件 2、在生命周期中引入项目 beforeCreate () { var domModule = ...

  • Gson的使用--使用注解

    Gson为了简化序列化和反序列化的过程,提供了很多注解,这些注解大致分为三类,我们一一的介绍一下。 自定义字段的名...

  • 记录使用iframe的使用

    默认记录一下----可以说 这是我第一次使用iframe 之前都没有使用过; 使用方式: 自己开发就用了这几个属...

  • with的使用

    下面例子可以具体说明with如何工作: 运行代码,输出如下

  • this的使用

    什么是this? this是一个关键字,这个关键字总是返回一个对象;简单说,就是返回属性或方法“当前”所在的对象。...

网友评论

    本文标题:RxAndroidBLE 的使用

    本文链接:https://www.haomeiwen.com/subject/pxsnsttx.html