简体   繁体   English

如何打破while循环?

[英]How to break while loop?

In my service i have the below code and i want to break the loop when flag is set to true.在我的服务中,我有以下代码,当标志设置为 true 时,我想中断循环。 It works well except when internet connection is slow or poor.它运行良好,除非互联网连接缓慢或较差。 Then as it sticks to the download part, the loop won't break efficiently.然后当它坚持下载部分时,循环不会有效地中断。 Any workarounds?任何解决方法? A solution is using a timer which periodically (every 500 ms) checks the flag state.一种解决方案是使用一个定时器,它会定期(每 500 毫秒)检查一次标志状态。 But i don't know how to break the loop when the flag is set to true!但是当标志设置为 true 时,我不知道如何打破循环!

static boolean flag = false;

public int onStartCommand(Intent intent, int flags, int startId) {              
    new Thread (new Runnable (){
        @Override
        public void run() {
            foo();
        }
    }).start();      
    return START_STICKY;
}

void foo(){      
    try{            
        while(true){
            if (flag)
                return;
            //download some data which takes a few seconds
        }
    } catch (Exception e){
    }
} 

You use the break;你使用break; keyword to break out of a loop.跳出循环的关键字。 So for you it might look something like this in your loop:所以对你来说,它在你的循环中可能看起来像这样:

if(condition) {
    break;
}

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

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