问题描述
我已经配置了将数据发送到Android App的蓝牙设备。 但是我正在接收不可读格式的数据。
我从蓝牙接收的数据是以下格式。
���
��
���
这是我的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,bytes)
Log.e("Arduino Message",readMessage.toString())
handler?.obtainMessage(MESSAGE_READ,readMessage)?.sendToTarget()
} catch (e: IOException) {
handler?.obtainMessage(CONNECTING_STATUS,-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()
}