Android进阶Android开发

RxAndroidBLE 的使用

2016-08-23  本文已影响3246人  linheimx
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 来解释可能存在的错误。

上一篇下一篇

猜你喜欢

热点阅读