【问题标题】:Decode Data Received from Bluetooth device in Android Kotlin?在 Android Kotlin 中解码从蓝牙设备接收的数据?
【发布时间】:2021-02-13 15:20:21
【问题描述】:

我已经配置了向 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
                }
            }
        }

【问题讨论】:

    标签: android kotlin bluetooth decode


    【解决方案1】:

    请通过 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()
    }
    

    【讨论】:

    • 你好,现在我正在获取十六进制字符串,但我怎样才能从中获取可读(实际数据)?
    • 读取设备规格。有关于解密响应的信息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多