等待Java for循环中出现状态



更新:

我在这里提出了一个新的、更具体的问题:在多个传感器连接之间实现wait((和notify((

旧问题:

我正在尝试使用一个按钮通过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则代码执行将暂停一秒钟,然后重试(再次询问状态(。我相信,如果有问题的话,也可以在不妨碍睡眠的情况下完成。

最新更新