简体   繁体   English

等到 Java for 循环中出现状态

[英]Wait until state occur in Java for loop

UPDATE:更新:

I made a new and more specific question here: Implementing wait() and notify() between multiple sensor connections我在这里提出了一个新的更具体的问题: 在多个传感器连接之间实现 wait() 和 notify()

OLD QUESTION:老问题:

I am trying to connect to multiple devices through Bluetooth in my Android app using a single button.我正在尝试使用一个按钮在我的 Android 应用程序中通过蓝牙连接到多个设备。 It works fairly ok, but sometimes the devices doesn't finish connecting before continuing to the next device in the for loop.它工作得相当好,但有时设备在继续到 for 循环中的下一个设备之前没有完成连接。

Every sensor connection state can have four states.每个传感器连接状态可以有四种状态。 I would like to have my for loop wait until state 2 has been reached before continuing to the next sensor.我想让我的 for 循环等到达到状态 2,然后再继续下一个传感器。 Is that possible?那可能吗? I Tried implementing a while loop, but it doesn't work.我尝试实现一个 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) {
            }
        }
    }
}

You can try something like this:你可以尝试这样的事情:

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
    }
}

If state != 2 than code execution will be paused for a sec, than it retries (asks for the state again).如果 state != 2 则代码执行将暂停一秒钟,然后重试(再次请求状态)。 I'm sure it can be done without a blocking sleep too if it's a problem.如果有问题,我相信它也可以在不阻塞睡眠的情况下完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM