我想获取/读取连接了两个安卓设备后传递的数据,到目前为止,我在它们之间配对、连接和传输信息,但不确定如何实现读取部分,这里我不确定是否应该使用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如果有人能指导我让数据读取部分工作,我将不胜感激。谢谢。
发布于 2014-09-04 21:36:45
看看Android附带的Android的BluetoothChat示例。我觉得它能做你想做的事。
$ANDROID_SDK/samples/android-19/legacy/BluetoothChat/src/com/example/android/BluetoothChat
发布于 2014-09-05 00:34:13
阅读管理连接部分。它清楚地写在文档中,如何通过蓝牙在设备之间交换(读/写)信息。http://developer.android.com/guide/topics/connectivity/bluetooth.html
https://stackoverflow.com/questions/25648208
复制相似问题