我有两个要连接的 Android 设备,使用蓝牙并通过 RFCOMM 通道传输数据。我只有一个设备接收数据,而另一个设备发送它......
使用此代码,我可以连接到其他设备并开始收听 RFCOMM 频道:
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
socket = (BluetoothSocket) m.invoke(device, 2);
socket.connect();
class BasicThread implements Runnable{
public void run() {
try {
InputStream stream = socket.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(stream));
while (true){
Log.d("myapp", "now listening...");
latestLine = r.readLine();
Log.d("myapp", latestLine);
}
} catch (IOException e) {
}
}
}
new Thread(new BasicThread()).run();
使用另一个设备,我实现了一个监听套接字,如下所示:
Method m = blue.getClass().getMethod("listenUsingRfcommOn", new Class[] { int.class });
BluetoothServerSocket socket = (BluetoothServerSocket) m.invoke(blue, 2);
BluetoothSocket sock = socket.accept();
Log.d("myapp", "Connected...\n\n\n\n\n\n\n\n");
OutputStream s = sock.getOutputStream();
final PrintWriter out = new PrintWriter(s);
它们都连接在 RFCOMM 通道 2 上,并且都互相看到对方,但是,第二个设备始终在BluetoothSocket sock = socket.accept();
有什么帮助吗?