有什么办法可以在循环内运行一个处理程序吗? 我有这样的代码,但不工作,因为它不等待循环,但执行的代码正确方法:Android的postDelayed处理程序内的For循环?
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
public void run() {
// need to do tasks on the UI thread
Log.d(TAG, "runn test");
//
for (int i = 1; i < 6; i++) {
handler.postDelayed(this, 5000);
}
}
};
// trigger first time
handler.postDelayed(runnable, 0);
当然,当我移动延迟循环作品外的职位,但它不重复,也不执行时代我需要:
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
public void run() {
// need to do tasks on the UI thread
Log.d(TAG, "runn test");
//
for (int i = 1; i < 6; i++) {
}
// works great! but it does not do what we need
handler.postDelayed(this, 5000);
}
};
// trigger first time
handler.postDelayed(runnable, 0);
发现的解决方案:
我需要用的Thread.sleep(5000)在doInBackground方法一起使用asyntask:
class ExecuteAsyncTask extends AsyncTask<Object, Void, String> {
//
protected String doInBackground(Object... task_idx) {
//
String param = (String) task_idx[0];
//
Log.d(TAG, "xxx - iter value started task idx: " + param);
// stop
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//
Log.d(TAG, "xxx - iter value done " + param);
return " done for task idx: " + param;
}
//
protected void onPostExecute(String result) {
Log.d(TAG, "xxx - task executed update ui controls: " + result);
}
}
for(int i = 0; i < 6; i ++){
//
new ExecuteAsyncTask().execute(String.valueOf(i));
}
如果你打电话'postDelayed' N次'Runnable'将运行N次了,是不是你想要的? – pskink
是的,但它不会等待并立即触发代码,这是我不希望 –
将'5000'更改为'5000 + i * 1000',所以第一个'Runnable'将在5秒后运行,第二个6秒后秒等... 7,8,9,... – pskink