title: Android Sleep/Wait/Delay function
body: <p>first of all, I'm a beginner to android world so please apologize me if it is stupid question..</p>
  
  <p>I'm trying to do following:</p>
  
  <ol>
  <li>Enable Mobile Data<br/></li>
  <li>Wait for 10 seconds<br/></li>
  <li>a. check if Mobile got IP address (data connected sucessfully)<br/>
  b. if Not connected,Disable Data<br/>
  c. Go to step 1<br/></li>
  </ol>
  
  <p>And these steps 1 to 3 are getting executed in For loop for User Given number of retries.</p>
  
  <p>Now my problem is: I'm stuck at step No. 2.<br/> I'm unable to make <code>waitfor(int seconds)</code> function. I tried using Runnable PostDelayed method but it is not giving me required output.</p>
  
  <pre><code>for(retry = UserChoice; retry &gt; 0 &amp;&amp; !isDataAvailable ; retry -- ){
       enableInternet()
       delay(10)
       isDataAvailable = GetInternetAvailibility()
       if(!isDataAvailable){ 
           disableInternet()
       }
  }
  </code></pre>
  
  <p>I tried to put <code>isDataAvailable = GetInternetAvailibility()</code> statement in <code>postDelayed</code> of handler but it is causing <code>enableInternet()</code> <code>disableInternet()</code> to execute at the same time while <code>isDataAvailable = GetInternetAvailibility()</code> gets executed after delay.</p>
  
  <p>I can see from logs, that <code>enableInternet()</code> executes for <code>UserChoice</code> number of times without any delay.</p>
  
  <p>Thread.sleep(10000) just freezes the UI for 10 seconds... How do I achieve this?</p>
  
  <p>EDIT : Let me clear :</p>
  
  <pre><code>public void onClick(View v) {
       // Perform action on click
      for(i=0; i&lt;3; i++ ){
          System.out.println("Before..");
          delay(5);
          System.out.println("after..");
      }
  }
  
  public void delay(int seconds){
      milliseconds = seconds * 1000;
      runOnUiThread(new Runnable() {
               @Override
               public void run() {
                    final Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                         @Override
                         public void run() {
                             System.out.println("XXX");                 //add your code here
                         }
                    }, milliseconds);
               }
        });
  }
  </code></pre>
  
  <p>Now whenever I click button I can see in logs that System.out prints message as:<br/><br/>
  Before<br/>
  after<br/>Before<br/>
  after<br/>Before<br/>
  after<br/>
  XXX<br/>XXX<br/>XXX<br/>
  <br/>
  But I want:<br/>
  Before<br/>
  XXX<br/>
  After.<br/>Before<br/>
  XXX<br/>
  After.<br/>Before<br/>
  XXX<br/>
  After.<br/></p>