问题描述
更新:
我在这里提出了一个更具体的新问题:Implementing wait() and notify() between multiple sensor connections
旧问题:
我正在尝试使用一个按钮通过Android应用程序中的蓝牙连接到多个设备。一切正常,但是有时设备无法完成连接,然后再继续for循环中的下一个设备。
每个传感器连接状态可以具有四个状态。我想让我的for循环等到状态2到达后再继续下一个传感器。那可能吗?我尝试实现了while循环,但是没有用。
public void onConnectSensors() {
for (int i = 0; i < 10; i++) { // Connect to sensors 0-9
int state = mScanAdapter.getConnectionState(i);
BluetoothDevice device = mScanAdapter.getDevice(i);
switch (state) {
case CONN_STATE_disCONNECTED:
...
case CONN_STATE_CONNECTING:
...
case CONN_STATE_CONNECTED:
...
case CONN_STATE_RECONNECTING:
...
}
while (mScanAdapter.getConnectionState(i) != 2) {
try {
wait(); // waits until state 2 has been reached
} catch (InterruptedException e) {
}
}
}
}
解决方法
您可以尝试以下操作:
public void onConnectSensors() {
for (int i = 0; i < 10; i++) { // Connect to sensors 0-9
int state = mScanAdapter.getConnectionState(i);
BluetoothDevice device = mScanAdapter.getDevice(i);
while (state != 2) {
// handle other states here if you want
try {
Thread.sleep(1000); //sleep a second before retry
} catch (Exception e) {
// handle errors
}
state = mScanAdapter.getConnectionState(i);
}
// handle state 2 here
}
}
如果状态= 2,则代码执行将暂停一秒,然后重试(再次请求状态)。我敢肯定,如果有问题,也可以在不阻塞睡眠的情况下完成。