如何在 Android 上处理 BLE 通知?

问题描述

我正在开发 nRF52840 和 Android 智能手机之间的帧交换序列。 实现了 nRF52840 端,我现在正在使用 Kotlin 实现 Android 应用程序。

应用程序使用“写入”来发送帧,而 nRF52840 使用“通知”来回复

我首先测试了与 nRF Connect 应用程序的交换,以将帧发送到 nRF52。正如您在下面看到的,nRF52 可以很好地响应通知并以十六进制格式发送帧:

点击 here 查看图片

在 Android 应用程序方面,我知道如何检测通知,但我希望像在 nRF Connect 应用程序中一样,能够显示这些帧(以十六进制格式),然后能够浏览它们。

我该怎么做?

我的 Kotlin 函数的开始:

    private fun handleNotification(characteristic: BluetoothGattCharacteristic) {
      println("Notification !")
      val newValue = characteristic.value
    }

解决方法

我对我的问题有了第一个答案。一个解决方案可能是使用这样的 getIntValue 函数:

private fun handleNotification(characteristic: BluetoothGattCharacteristic) {
  println("Notification !")
  val newValue = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8,0)
  println("value : $newValue")
  val newValue2 = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8,1)
  println("value : $newValue2")
}

但是如果我通过调用一次函数来获得 ByteArray 会更好。

,

我的问题有另一个答案。以下代码以十六进制格式显示通过通知发送的 ByteArray 的全部内容:

private fun handleNotification(characteristic: BluetoothGattCharacteristic) {
    println("Notification !")
    val data: ByteArray? = characteristic.value
    if (data?.isNotEmpty() == true) {
        val hexString: String = data.joinToString(separator = " ",prefix = "[",postfix = "]") {
            String.format("0x%02X",it)
        }
        println(hexString)
    } else {
        println("Data is empty")
    }
}

输出:

I/System.out: [0x00 0x05 0x00 0x01 0x02 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00]