我有以下功能可以通过蓝牙将数据发送到笔记本电脑上运行的蓝牙串行监视器。
private fun sendData(mSocket: BluetoothSocket?, data: String) { //mSocket: "XX:XX:XX:XX:6E:D0" data hello world!
if (mSocket == null) {
return
}
val outputStream: OutputStream
try {
outputStream = mSocket.outputStream //mSocket: "XX:XX:XX:XX:6E:D0"
} catch (e: IOException) {
Log.d("Outputstream", "Error occurred when creating output stream: ${e.message}")
return
}
try {
val dataWithNewline = "$data\n"
outputStream.write(dataWithNewline.toByteArray())
outputStream.flush()
Log.d("sendData", "Data sent: $data")
} catch (e: IOException) {
Log.d("sendData", "Error occurred when sending data: ${e.message}")
}
}
蓝牙套接字已成功创建并连接,但是当我尝试发送数据时,没有任何反应。也不会抛出 IOException。在 Logcat 中,我看到“数据已发送:hello world!”表明数据已发送过来。然而在接收端我什么也没看到。在代码的注释中,当我在函数末尾放置断点时,我写下了一些变量值。为什么我的 MAC 地址显示为截断的:“XX:XX:XX:XX:6E:D0”?检查 mSocket 后,我确实在 mAddress 变量下看到了完整的 MAC 地址。
这是连接到我的设备的功能:
fun connectOBDDevice(deviceItem: BluetoothDeviceItem) {
val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
val device: BluetoothDevice? = mBluetoothAdapter.getRemoteDevice(deviceItem.address)
try {
val createInsecureRfcommSocket = BluetoothDevice::class.java.getMethod("createInsecureRfcommSocket", Int::class.javaPrimitiveType)
mSocket = createInsecureRfcommSocket.invoke(device, 1) as BluetoothSocket
} catch (e: Exception) {
// e.printStackTrace();
Log.d("connectOBDDevice", "createInsecureRfcommSocket failed")
}
if(mSocket != null)
{
if (ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.BLUETOOTH_CONNECT
) == PackageManager.PERMISSION_GRANTED
) {
try {
mSocket.connect()
val receiveThread = BluetoothReceiveThread(mSocket)
receiveThread.start()
Toast.makeText(context, "Device connected successfully!", Toast.LENGTH_SHORT).show()
}
catch (e: IOException)
{
Toast.makeText(context, "Connection Failed", Toast.LENGTH_SHORT).show()
}
}
}
}
如有任何帮助,我们将不胜感激!
我尝试使用手机上的“串行蓝牙”应用程序来测试连接,在使用时一切正常。
这个问题为我解决了这个问题。我需要指定并使用 UUID 进行串行通信:
val uuid: UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb") // UUID for serial communication
然后我编辑了代码以使用 UUID:
fun connectOBDDevice(deviceItem: BluetoothDeviceItem) {
val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
val device: BluetoothDevice? = mBluetoothAdapter.getRemoteDevice(deviceItem.address)
if (ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.BLUETOOTH_CONNECT
) == PackageManager.PERMISSION_GRANTED
) {
try {
mSocket = device?.createInsecureRfcommSocketToServiceRecord(BluetoothHelper.uuid)!! //Use the UUID here
} catch (e: Exception) {
Log.d("connectOBDDevice", "createInsecureRfcommSocket failed")
}
if (mSocket != null) {
try {
mSocket.connect()
val receiveThread = BluetoothReceiveThread(mSocket)
receiveThread.start()
Toast.makeText(context, "Device connected successfully!", Toast.LENGTH_SHORT)
.show()
} catch (e: IOException) {
Toast.makeText(context, "Connection Failed", Toast.LENGTH_SHORT).show()
}
}
}
}
如果不使用 UUID,数据将顺利发送出去,但无法正确接收。