我有这个代码。在我的代码中我需要延迟操作开始(它工作正常)但在操作中我需要检查InitInProcess()值。如果为false则为break循环,如果为true,则等待500ms并再次检查。但结果我得知检查结果是imediatly而不是每500ms。
Handler myHandler = new Handler();
myHandler.postDelayed(new Runnable() {
@Override
public void run() {
int test = 0;
while (test!=20)
{
if (InitInProcess())
break;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("MyApp", ""+test);
test++;
}
}
}, 3000);
记录(查看时间):
02-27 12:48:41.707: D/MyApp(10082): 0
02-27 12:48:42.212: D/MyApp(10082): 1
02-27 12:48:42.712: D/MyApp(10082): 2
02-27 12:48:43.267: D/MyApp(10082): 3
02-27 12:48:43.767: D/MyApp(10082): 4
02-27 12:48:44.272: D/MyApp(10082): 5
02-27 12:48:44.772: D/MyApp(10082): 6
02-27 12:48:45.277: D/MyApp(10082): 7
02-27 12:48:45.777: D/MyApp(10082): 8
02-27 12:48:46.277: D/MyApp(10082): 9
02-27 12:48:46.777: D/MyApp(10082): 10
02-27 12:48:47.277: D/MyApp(10082): 11
02-27 12:48:47.772: D/MyApp(10082): 12
02-27 12:48:48.277: D/MyApp(10082): 13
02-27 12:48:48.777: D/MyApp(10082): 14
02-27 12:48:49.277: D/MyApp(10082): 15
02-27 12:48:49.777: D/MyApp(10082): 16
02-27 12:48:50.277: D/MyApp(10082): 17
02-27 12:48:50.782: D/MyApp(10082): 18
02-27 12:48:51.277: D/MyApp(10082): 19
答案 0 :(得分:2)
int test = 0;
while (test!=20){
if (InitInProcess())
break;
try {
myHandler.postDelayed(new Runnable() {
test++;
Log.d("MyApp", ""+test);
},500);
} catch (Exception e) {
e.printStackTrace();
}
}
答案 1 :(得分:1)
private static final long RETRY_DELAY = 500;
private static final int RETRY_COUNT = 10;
private Handler myHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
if (!InitInProcess() && msg.what>0) {
myHandler.sendEmptyMessageDelayed(msg.what-1, RETRY_DELAY);
}
}
};
myHandler.sendEmptyMessageDelayed(RETRY_COUNT, RETRY_DELAY);