如何在android中通过蓝牙向配对设备发送文本消息?
在我的应用程序中,我想通过蓝牙发送和接收短信。我可以在列表视图中看到配对设备名称和地址的列表。但是,当我试图向配对设备发送文本时,什么都不会发生。在其他设备中,没有接收到文本 这是我向配对设备发送消息的代码如何在android中通过蓝牙向配对设备发送文本消息?,android,bluetooth,stream,android-bluetooth,Android,Bluetooth,Stream,Android Bluetooth,在我的应用程序中,我想通过蓝牙发送和接收短信。我可以在列表视图中看到配对设备名称和地址的列表。但是,当我试图向配对设备发送文本时,什么都不会发生。在其他设备中,没有接收到文本 这是我向配对设备发送消息的代码 private void sendDataToPairedDevice(String message, String adress) { byte[] toSend = message.getBytes(); try { Bluetoo
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);
}
}
bluetoothchat示例实际上是使用BluetoothAPI的新手的最佳选择 假设您的应用程序只使用一个活动,即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聊天中评论或删除有错误的部分,这些部分实际上就是用户界面中已删除或更改的部分
我知道代码可能听起来很混乱,但这是尽快使用它的最简单的方法,看视频教程或文本教程几个小时只会让它变得更复杂,相信我,我以前试过 短信只能通过短信网关发送,不能通过蓝牙发送?@Ryan,OP在哪里提到他想发送短信?我想通过蓝牙发送。哦,让我们假设我想发送其他东西,但只通过蓝牙。我正在成功获取所有蓝牙设备的名称和地址,现在我想发送一些东西到特定的设备。@user3243163我的假设是
文本消息
指的是短信息,而不是包含短信息以外文本的文字信息。@KanchaEkant您是从BluetoothChat示例应用程序中获得此代码的吗?