【问题标题】:Observing connection state with RXAndroidBlE使用 RXAndroidBlE 观察连接状态
【发布时间】:2019-03-08 23:43:24
【问题描述】:

我正在尝试听我的应用是否连接到蓝牙设备。我正在尝试打印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】:

    上面的代码有两点:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      • 1970-01-01
      • 2011-11-24
      相关资源
      最近更新 更多