我在连接时遇到问题。起初它有效,而不是它不,除非我取消配对设备。我已经得到了所有可能发生的异常,套接字关闭、管道关闭、连接被拒绝、端口已在使用等。
我知道 android pre 4.2 ( https://code.google.com/p/android/issues/detail?id=37725 ) 上的蓝牙存在问题。
我在连接这些设备时遇到问题的设备:
- HTC一(安卓4.2)
- 三星galaxy s2(android 4.1.2)
- 关系 4 (4.3)
- 三星银河 s4 (4.2)
另一个小问题是,配对的设备没有存储(主要在 nexus 4 和 sgs2 上)。
这是我的代码:
private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //this is the other one that I've tried: fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME = "BluetoothConnector";
public void listenForConnection() throws IOException, BluetoothException {
//first close the socket if it is open
closeSocket();
BluetoothServerSocket mServerSocket = null;
try {
mServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID_SECURE); //ioexception here!
} catch (IOException e) {
if (Build.VERSION.SDK_INT >= 9) {
try { //this is a stupid hack, http://stackoverflow.com/questions/6480480/rfcomm-connection-between-two-android-devices
Method m = mBluetoothAdapter.getClass().getMethod("listenUsingRfcommOn", new Class[] { int.class });
mServerSocket = (BluetoothServerSocket) m.invoke(mBluetoothAdapter, PORT);
} catch (Exception ex) {
Log.e(ex);
throw e;
}
} else {
throw e;
}
}
while (!isCancelled) {
try {
socket = mServerSocket.accept();
} catch (IOException e) {
if (socket != null) {
try {
socket.close();
} finally {
socket = null;
}
}
throw e;
}
if (socket == null) {
throw new BluetoothException("Socket connection connected, but null");
} else {
isConnected = true;
break; // everything is ok
}
}
}
public void connect(String address) throws IOException, BluetoothException {
mBluetoothAdapter.cancelDiscovery();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
try {
socket = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} catch (IOException e1) {
Log.e(e1);
if (Build.VERSION.SDK_INT >= 9) {
try {
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
socket = (BluetoothSocket) m.invoke(device, PORT);
} catch (Exception e) {
Log.e(e);
throw e1;
}
} else {
throw e1;
}
}
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket.connect();
} catch (IOException e) {
Log.e(e);
// Close the socket
try {
socket.close();
} catch (IOException e2) {
Log.e(e2);
Log.wtf("unable to close() socket during connection failure");
}
throw e;
}
}
private void closeSocket() {
try {
if (socket != null) {
socket.close();
socket = null;
Log.d("Socket closed");
}
} catch (IOException e) {
Log.e(e);
Log.wtf("close() of connect socket failed");
}
}
我尝试更改 uuid(也是随机的),尝试查看较旧的 sdk 样本。那么这里有什么问题呢?
编辑:试图澄清:问题通常出现,当 2 个已配对、连接、成功通信的设备(由用户)断开连接时。之后,它们将无法重新连接,除非它们重新启动或手动取消配对。