它也发生在我的测试中。我是 BluetoothChat 示例代码,您应该查看 connectionLost 方法。我不记得是否有任何变量可以保持丢失的连接数,但您可以自己添加。在 connectionLost 方法中,测试丢失的连接数是否小于预定义的数量(在我的情况下为 3)。如果是这样,请使用 mHandler(吐司)向 UI 发送一条消息,然后再次调用 connect(device)。如果不是这样(您失去连接超过 3 次),请调用 stop() 方法。
还要确保像这样在 ConnectThread 中打开套接字:
public ConnectThread(BluetoothDevice device, boolean isSecure) {
mmDevice = device;
BluetoothSocket tmp = null;
mSocketType = isSecure ? "Secure" : "Insecure";
// Get a BluetoothSocket for a connection with the given BluetoothDevice
if (isSecure) {
// reflection is better to use
Method m = null;
try {
Log.d(TAG, "create reflection");
m = device.getClass().getMethod("createRfcommSocket",new Class[] { int.class });
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
mmSocketFallBack = tmp;
} else {
Log.d(TAG, "create insecure");
try {
tmp = device
.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
}
mmSocket = mmSocketFallBack;
}
您的 connectionLost 应该类似于:
public void connectionLost() {
init = false;
Log.d(TAG, "connectionLost -> " + mConnectionLostCount);
mConnectionLostCount++;
if (mConnectionLostCount < 3) {
// Send a reconnect message back to the Activity
Message msg = mHandler.obtainMessage(cBluetooth.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(WebAppInterface.TOAST, "Connection lost. Reconnecting...");
msg.setData(bundle);
mHandler.sendMessage(msg);
connect(mSavedDevice,true);
} else {
mConnectionLostCount = 0;
Message msg = mHandler.obtainMessage(cBluetooth.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(WebAppInterface.TOAST,"Device connection was lost!");
msg.setData(bundle);
mHandler.sendMessage(msg);
cBluetooth.this.stop();
}
}
我希望你能适应你的情况。您也可以查看此链接,它们对我帮助很大:
- 遥控器示例
- 连接死机解决方案
- 从中获得灵感的蓝牙服务示例