在我的应用程序中,我想通过蓝牙发送和接收短信。我可以在列表视图中看到配对设备名称和地址的列表。但是当我尝试向配对设备发送文本时,什么也没有发生。在其他设备中没有收到文本。
这是我向配对设备发送消息的代码。
private void sendDataToPairedDevice(String message, String adress) {
byte[] toSend = message.getBytes();
try {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(adress);
// BluetoothSocket socket
// =device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"));
BluetoothSocket socket = null;
Method m = null;
try {
m = device.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
} catch (Exception e) {
e.printStackTrace();
}
try {
socket = (BluetoothSocket) m.invoke(device, 1);
} catch (Exception e) {
e.printStackTrace();
}
OutputStream mmOutStream = socket.getOutputStream();
mBluetoothAdapter.cancelDiscovery();
socket.connect();
mmOutStream.write(toSend);
} catch (Exception e) {
Log.d("TAG", "Exception during write", e);
}
}
如果您是蓝牙 API 的新手,那么 bluetoothchat 示例实际上是完美的选择。
假设您的应用程序仅使用一个 Activity,即 BluetoothChat 类:
要向您连接的设备发送文本,请使用 BluetoothChat 类中的“sendMessage(String message)”方法发送文本。
至于接收和处理文本,您还会在 bluetoothchat 类中的某处找到 handleMessage(Message msg) 方法,然后转到这部分:
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
看到 readMessage 字符串了吗?
这是您从其他设备收到的文本,现在您可以根据需要进行处理。
然后只需更改BluetoothChat类引用的主布局,然后在BluetoothChat聊天中注释或删除有错误的部分,这些部分实际上将是您在UI中删除或更改的部分。
我知道代码可能听起来很混乱,但这是尽可能快速使用它的最简单方法,观看视频教程或文本教程几个小时只会让它变得更加复杂,相信我,我以前尝试过这个。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)