简体   繁体   English

如何处理 Android 上的 BLE 通知?

[英]How to handle BLE notifications on Android?

I'm developing a frame exchange sequence between an nRF52840 and an Android smartphone.我正在开发 nRF52840 和 Android 智能手机之间的帧交换序列。 The nRF52840 side is implemented and I am now implementing the Android application with Kotlin. nRF52840端实现了,我现在用Kotlin实现Android应用。

The application uses "writes" to send frames and the nRF52840 uses "notifications" to reply.应用程序使用“写入”来发送帧,nRF52840 使用“通知”来回复。

I first tested the exchange with the nRF Connect application to send frames to the nRF52.我首先测试了与 nRF Connect 应用程序的交换,以将帧发送到 nRF52。 As you can see below, the nRF52 responds well with notifications and sends frames in hexadecimal format:正如您在下面看到的,nRF52 可以很好地响应通知并以十六进制格式发送帧:

Click here to see the image.单击此处查看图像。

On the Android application side, I know how to detect notifications but I would like, as in the nRF Connect application, to be able to display these frames (in hexadecimal format) and then be able to browse them.在 Android 应用程序方面,我知道如何检测通知,但我希望像在 nRF Connect 应用程序中一样,能够显示这些帧(十六进制格式),然后能够浏览它们。

How can I do that?我怎样才能做到这一点?

Beginning of my Kotlin function:我的Kotlin function开头:

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

I have a first answer to my question.我有一个问题的第一个答案。 A solution could be to use getIntValue function like that:一种解决方案可能是像这样使用 getIntValue function:

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

But it would be better if I had a ByteArray by calling a function once.但是,如果我通过一次调用 function 来获得一个 ByteArray 会更好。

I have another answer to my question.我的问题有另一个答案。 The following code displays the entire content of a ByteArray sent through a notification in hexadecimal format:以下代码以十六进制格式显示通过通知发送的 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")
    }
}

Output: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM