我正试图在安卓手机/平板电脑(4.0.3)和蓝牙设备之间建立蓝牙通信,蓝牙设备是一个耳环阅读器(Destron Fearring DTR3E,如果你想知道的话,我想你不会知道)。
我从蓝牙设置中将手机与读卡器配对(读卡器的标签上有配对密码),蓝牙当然是打开的,现在我正试图通过蓝牙服务器套接字收听设备上的读数。问题是接受电话再也回不来了,所以很明显我做错了什么。通信是使用RFCOMM完成的。
代码:
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
String uuid = "00001101-0000-1000-8000-00805F9B34FB";
tmp = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("pdfParserServer", UUID.fromString(uuid));
} catch (Exception e) {
e.printStackTrace();
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
try {
mmServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
我有什么东西不见了吗?
谢谢!
唯一可能导致代码永远无法从accept返回的原因是,您试图连接的设备"Destron Fearring DTR3E"实际上有一个蓝牙服务器插座,而不是蓝牙客户端,因此,该设备可能正在等待您真正连接到它,与其你创建一个bluetoothserver套接字并等待它连接到你的android设备,你应该阅读设备上的规格,并确保实际上是你必须在"Destron Fearring DTR3E"套接字上打开连接。。。
希望这能帮助。。。
问候!