使用RXAndroidBlE观察连接状态

时间:2019-03-08 23:43:24

标签: android kotlin bluetooth-lowenergy rx-android rxandroidble

我正在尝试听我的应用程序是否已连接到蓝牙设备。我正在尝试打印connectionState结果,但是应用程序甚至没有达到第一个println,因此我无法检查它们可能是什么。我想枚举可能的连接状态,然后调整UI作为响应。我该怎么办?

val rxBleClient = RxBleClient.create(this.context!!)
val bleDevice = rxBleClient.getBleDevice("34:81:F4:3C:2D:7B")

val disposable = bleDevice.establishConnection(true) // <-- autoConnect flag
 .subscribe({
  rxBleConnection ->

  // All GATT operations are done through the rxBleConnection.
  bleDevice.observeConnectionStateChanges()
  .subscribe({
   connectionState ->
   println("Connection State: $connectionState")

   if (connectionState != null) {
    enableBluetooth.setBackgroundResource(R.drawable.bluetooth_on) // Change image
    deviceConnected.setText(R.string.connected_to_hooplight) // Changed text
   } else {
    enableBluetooth.setBackgroundResource(R.drawable.bluetooth_off) // Change image
    deviceConnected.setText(R.string.connect_to_hooplight) // Changed text
   }

  }, {
   throwable ->
   Log.d("Error: ", throwable.toString())
  })
 }, {
  throwable ->
  // Handle an error here.
  Log.d("Error: ", throwable.toString())
 })

// When done... dispose and forget about connection teardown :)
disposable.dispose()

1 个答案:

答案 0 :(得分:2)

上面的代码有两件事:

    当不再需要已订阅的流时,应调用
  1. disposable.dispose()。如果在订阅后立即调用dispose方法,则实际上不会发生任何事情。这就是为什么甚至第一个println都不会出现的原因。
  2. bleDevice.establishConnection()bleDevice.observeConnectionStateChanges()在功能上并不相互依赖。不必建立连接即可观察更改。即使在连接打开后就开始观察更改,它也只会在关闭连接时获得信息(因为这是自此以来的第一个更改

更好的方法是将观察的连接更改流与实际的连接分离。示例代码:

val observingConnectionStateDisposable = bleDevice.observeConnectionStateChanges()
    .subscribe(
        { connectionState ->
            Log.d("Connection State: $connectionState")

            if (connectionState == RxBleConnectionState.CONNECTED) { // fixed the check
                enableBluetooth.setBackgroundResource(R.drawable.bluetooth_on) // Change image
                deviceConnected.setText(R.string.connected_to_hooplight) // Changed text
            } else {
                enableBluetooth.setBackgroundResource(R.drawable.bluetooth_off) // Change image
                deviceConnected.setText(R.string.connect_to_hooplight) // Changed text
            }
        },
        { throwable -> Log.d("Error: ", throwable.toString()) }
    )

val connectionDisposable = bleDevice.establishConnection(false)
    .subscribe(
        { Log.d("connection established") }, // do your thing with the connection
        { throwable -> Log.d("Error on connection: ${throwable}") }
    )