简体   繁体   中英

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. 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. But i don't know how to break the loop when the flag is set to 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; keyword to break out of a loop. So for you it might look something like this in your loop:

if(condition) {
    break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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