【发布时间】:2014-10-28 04:24:29
【问题描述】:
我希望在连接几个 Android 设备后获取/读取我传递的数据,到目前为止我在它们之间配对、连接和传输信息,但不知道如何实现读取部分,这里我不是确定我是否应该使用 createRfcommSocketToServiceRecord 或 listenUsingRfcommWithServiceRecord 来为此目的创建读取套接字。
我有两个屏幕,一个是用户按下一个按钮并传输信息,另一个是接收器按下另一个按钮并读取数据,我想知道同步是否不正确,在我按下“发送”按钮后然后“读取”按钮连接不可用,或者如果此实现不推荐一起使用。
这是我的两次尝试:
尝试 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
如果有人能指导我让数据读取部分正常工作,我将不胜感激。谢谢。
【问题讨论】:
标签: java android bluetooth data-transfer