在我的测试中也遇到过这个问题。在BluetoothChat示例代码中,你应该查看connectionLost方法。我不记得是否有任何变量来保留失去连接的次数,但你可以自己添加。在connectionLost方法中,检测失去连接的次数是否小于一个预定义的数字(在我的情况下是3)。如果为真,则使用mHandler向UI发送消息(一条toast)并再次调用connect(device)。如果不是这样(你失去了超过3次连接),则调用stop()方法。
此外,请确保在ConnectThread中以以下方式打开套接字:
public ConnectThread(BluetoothDevice device, boolean isSecure) {
mmDevice = device;
BluetoothSocket tmp = null;
mSocketType = isSecure ? "Secure" : "Insecure";
if (isSecure) {
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) {
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();
}
}
我希望您能根据自己的情况进行调整。您还可以查看以下链接,它们对我很有帮助:
- 远程控制示例
- 连接断开解决方案
- 蓝牙服务示例以供参考