title: Android postDelayed Handler Inside a For Loop?
body: <p>Is there any way of running a handler inside a loop? 
  I have this code but is not working as it does not wait for the loop but executes the code right way:</p>
  
  <pre><code>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 &lt; 6; i++) {
  
                      handler.postDelayed(this, 5000);
  
                  }
  
  
              }
          };
  
          // trigger first time
          handler.postDelayed(runnable, 0);
  </code></pre>
  
  <p>Of course when I move the post delayed outside the loop works but it does not iterate nor execute the times I need:</p>
  
  <pre><code>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 &lt; 6; i++) {
                  }
  
                  // works great! but it does not do what we need
                  handler.postDelayed(this, 5000);
  
  
              }
          };
  
          // trigger first time
          handler.postDelayed(runnable, 0);
  </code></pre>
  
  <p><strong>SOLUTION FOUND:</strong></p>
  
  <p>I need to use asyntask along with Thread.sleep(5000) in the doInBackground method:</p>
  
  <pre><code>class ExecuteAsyncTask extends AsyncTask&lt;Object, Void, String&gt; {
  
  
              //
              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 &lt; 6; i ++){
  
              //
              new ExecuteAsyncTask().execute( String.valueOf(i) );
  
          }
  </code></pre>