所以我有这个Android蓝牙项目,我遇到了一个非常烦人的问题;让我描述一下上下文:
将要连接的两部手机使用 android 开发者网站(此处)上的蓝牙文档中描述的确切方法获取它们的蓝牙套接字;因此,我使用以下线程进行连接:
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
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) { }
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)
manageConnectedSocket(socket);
try {
mmServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
那是接受线程,
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
那就是 ConnectThread;(你可能会注意到它们确实是从上面的链接复制的);
问题是在尝试连接的时候,connectthread实际上返回了一个socket(调用managesocket()),但是接受线程却停留在socket = mmServerSocket.accept(),就好像什么都不会发生一样;但是AcceptThread中确实发生了一些事情,因为当我从另一台设备(具有ConnectThread的设备)启动连接时,正在更新接受设备的logcat;有时连接实际上是正确创建的,但只有在强制关闭、禁用->启用蓝牙等之后。
这是 logcat 中有趣的一行(我猜是由 .accept() 调用生成的):
07-19 18:04:47.484: D/BLZ20_WRAPPER(3143): btlif_signal_event: ### 事件 BTLIF_BTS_RFC_CON_IND 不匹配 ###
那么可能是什么问题呢?