观察与RXAndroidBlE的连接状态

问题描述 投票:0回答:1

我正在试着听我的应用程序是否连接到蓝牙设备。我正在尝试打印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()
android kotlin bluetooth-lowenergy rx-android rxandroidble
1个回答
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}") }
    )
© www.soinside.com 2019 - 2024. All rights reserved.