在我的服务中我有以下代码,我想在flag设置为true时打破循环。它很好用,除非互联网连接缓慢或差。然后,当它坚持下载部分时,循环不会有效地中断。任何解决方法? 解决方案是使用定时器(周期性地每500毫秒)检查标志状态。但是,当标志设置为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){
}
}
答案 0 :(得分:0)
您使用break;
关键字来摆脱循环。所以对你来说,它可能在你的循环中看起来像这样:
if(condition) {
break;
}