2016-08-18 71 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