androidkotlinbluetooth-lowenergynrf52

How to handle BLE notifications on Android?


I'm developing a frame exchange sequence between an nRF52840 and an Android smartphone. The nRF52840 side is implemented and I am now implementing the Android application with Kotlin.

The application uses "writes" to send frames and the nRF52840 uses "notifications" to reply.

I first tested the exchange with the nRF Connect application to send frames to the nRF52. As you can see below, the nRF52 responds well with notifications and sends frames in hexadecimal format:

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.

How can I do that?

Beginning of my Kotlin function :

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

Solution

  • I have another answer to my question. The following code displays the entire content of a ByteArray sent through a notification in hexadecimal format:

    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 :

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