使用 RXAndroidBlE 观察连接状态

Observing connection state with 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. disposable.dispose()。如果在订阅后立即调用 dispose 方法,实际上什么也不会发生。这就是为什么连第一个 println 都没有出现的原因。
  2. bleDevice.establishConnection()bleDevice.observeConnectionStateChanges() 在功能上不相互依赖。不必建立连接来观察变化。即使在连接开启后开始观察变化,它也只会在连接关闭时获取信息(因为这是自那时以来的第一个 change

更好的方法是分离观察连接变化流和实际连接。示例代码:

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}") }
    )