2016-08-18 63 views
1

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

     } 
+0

如果你打電話'postDelayed' N次'Runnable'將運行N次了,是不是你想要的? – pskink

+0

是的,但它不會等待並立即觸發代碼,這是我不希望 –

+0

將'5000'更改爲'5000 + i * 1000',所以第一個'Runnable'將在5秒後運行,第二個6秒後秒等... 7,8,9,... – pskink

回答

8

下面的代碼應該這樣做:

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, "runn test"); 


       if (count++ < 5) 
        handler.postDelayed(this, 5000); 

      } 
     }; 

     // trigger first time 
     handler.post(runnable); 
+0

爲什麼downvote(我試圖學習)? – Shaishav

+0

當做if(count ++ <6)時,它實際上增加了一個計數值?或者,如果(計數+ 1 <6)? – DAVIDBALAS1

+0

@ DAVIDBALAS1它會將當前值與6進行比較,然後增加下一次迭代的值 – Shaishav