【发布时间】:2016-08-18 17:50:28
【问题描述】:
有没有办法在循环中运行处理程序? 我有这段代码,但没有工作,因为它不等待循环,而是以正确的方式执行代码:
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);
找到解决方案:
我需要在 doInBackground 方法中使用 asyntask 和 Thread.sleep(5000):
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) );
}
【问题讨论】:
-
如果你调用
postDelayedN 次Runnable将运行N 次,这不是你想要的吗? -
是的,但它不会等待并立即触发代码,这是我不想要的
-
将
5000更改为5000 + i * 1000,因此第一个Runnable将在5 秒后运行,第二个在6 秒后运行,以此类推... 7、8、9、...跨度> -
你的答案很好,但也不起作用,它不会等待。
-
等什么?这是一个“延迟”执行,你还想等什么?
标签: java android multithreading handler