我希望得到/读取我连接几个Android设备后传递的数据,到目前为止我配对,连接并在它们之间传输信息,但不知道如何实现阅读部分,这里我不是确定我是否应该使用createRfcommSocketToServiceRecord或listenUsingRfcommWithServiceRecord为此目的创建读取套接字。
我有两个屏幕,一个是用户按下按钮并传输信息,另一个是接收器按下另一个按钮并读取数据,我想知道同步是否不正确以及我按下"发送& #34;按钮,然后"读"按钮连接不可用或者这个实现不能一起推荐。
这是我的两次尝试:
尝试1:
//Executed after the user press the read data button
private void connectToServerSocket(BluetoothDevice device, UUID uuid) {
try{
BluetoothServerSocket serverSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(device.getName(),uuid);
//Here is where I get the error:
//io to Server Socket JSR82 Connection is not created, failed or aborted
BluetoothSocket clientSocket = serverSocket.accept();
// Start listening for messages.
StringBuilder incoming = new StringBuilder();
listenForMessages(clientSocket, incoming);
// Add a reference to the socket used to send messages.
transferSocket = clientSocket;
} catch (IOException ioe) {
this.printToast("Excep io toServerSocket:" + ioe.getMessage());
} catch (Exception e) {
this.printToast("Excep toServerSocket:" + e.getMessage());
}
}
尝试2:
private void connectToServerSocket(BluetoothDevice device, UUID uuid) {
try{
BluetoothServerSocket clientSocket = device.createRfcommSocketToServiceRecord(uuid);
//clientSocket without method and invoke is not working either
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
clientSocket = (BluetoothSocket) m.invoke(device, 1);
//Here is where I get the error:
//io to Server Socket JSR82 Connection is not created, failed or aborted
clientSocket.connect();
// Start listening for messages.
StringBuilder incoming = new StringBuilder();
listenForMessages(clientSocket, incoming);
// Add a reference to the socket used to send messages.
transferSocket = clientSocket;
} catch (IOException ioe) {
this.printToast("Excep io toServerSocket:" + ioe.getMessage());
} catch (Exception e) {
this.printToast("Excep toServerSocket:" + e.getMessage());
}
}
在serverSocket.accept()
或clientSocket.connect()
我得到例外:
Connection is not created, failed or aborted
如果有人能指导我使数据阅读部分正常工作,我将不胜感激。感谢。
答案 0 :(得分:1)
查看Android SDK附带的Android的BluetoothChat示例。我认为它完全符合您的要求。
$ ANDROID_SDK /样品/机器人-19 /遗留/ BluetoothChat / SRC / COM /示例/机器人/ BluetoothChat
答案 1 :(得分:1)
阅读管理连接部分。 它清楚地写在文档中如何通过蓝牙在设备之间交换(读/写)信息。 http://developer.android.com/guide/topics/connectivity/bluetooth.html