在 Android Kotlin 中解码从蓝牙设备接收到的数据?

Decode Data Received from Bluetooth device in Android Kotlin?

我已经配置了发送数据到 Android 应用程序的蓝牙设备。 但是我收到的数据格式不可读。

我从蓝牙接收到的数据格式如下。

���
��
���

这是我的 android 代码

  private val mmInStream: InputStream?
        private val mmOutStream: OutputStream?

        init {
            var tmpIn: InputStream? = null
            var tmpOut: OutputStream? = null

            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = mmSocket.inputStream
                tmpOut = mmSocket.outputStream
            } catch (e: IOException) {
                Log.e(TAG, ": " + e.message)
            }
            mmInStream = tmpIn
            mmOutStream = tmpOut
        }

        override fun run() {
            val buffer = ByteArray(1024) // buffer store for the stream
            var bytes = 0 // bytes returned from read()
            // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                        bytes = mmInStream?.read(buffer) ?:0
                        val readMessage = String(buffer, 0, bytes)
                        Log.e("Arduino Message", readMessage.toString())
                        handler?.obtainMessage(MESSAGE_READ, readMessage)?.sendToTarget()
                } catch (e: IOException) {
                    handler?.obtainMessage(CONNECTING_STATUS, 0, -1)?.sendToTarget()
                    e.printStackTrace()
                    break
                }
            }
        }

请通过 bytesToHex 扩展方法将接收到的字节转换为十六进制字符串并记录下来

fun ByteArray.bytesToHexString(
    spaces: Boolean = false
): String {
    val format = if (spaces) "%02x " else "%02x"
    val sb = StringBuilder()
    for (i in 0 until size) {
        sb.append(format.format(this[i]))
    }
    return sb.toString()
}