有没有办法在循环中运行处理程序? 我有这段代码,但没有工作,因为它不等待循环,而是以正确的方式执行代码:
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) );
}
最佳答案
您可以让 Runnable
实例调用自身特定次数,而不是使用 for
循环。这些调用将发布到 UI 线程队列,因此请记住这一点。另外,由于延迟较大,请确保下次触发时仍然需要该事件。
下面的代码应该可以做到:
final Handler handler = new Handler();
int count = 0;
final Runnable runnable = new Runnable() {
public void run() {
// need to do tasks on the UI thread
Log.d(TAG, "Run test count: " + count);
if (count++ < 5) {
handler.postDelayed(this, 5000);
}
}
};
// trigger first time
handler.post(runnable);
关于java - Android postDelayed Handler 在 For 循环中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39024588/