有什麼辦法可以在循環內運行一個處理程序嗎? 我有這樣的代碼,但不工作,因爲它不等待循環,但執行的代碼正確方法: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