Android Sleep/Wait/Delay function

ShitalSavekar picture ShitalSavekar · Jan 27, 2014 · Viewed 78.5k times · Source

first of all, I'm a beginner to android world so please apologize me if it is stupid question..

I'm trying to do following:

  1. Enable Mobile Data
  2. Wait for 10 seconds
  3. a. check if Mobile got IP address (data connected sucessfully)
    b. if Not connected,Disable Data
    c. Go to step 1

And these steps 1 to 3 are getting executed in For loop for User Given number of retries.

Now my problem is: I'm stuck at step No. 2.
I'm unable to make waitfor(int seconds) function. I tried using Runnable PostDelayed method but it is not giving me required output.

for(retry = UserChoice; retry > 0 && !isDataAvailable ; retry -- ){
     enableInternet()
     delay(10)
     isDataAvailable = GetInternetAvailibility()
     if(!isDataAvailable){ 
         disableInternet()
     }
}

I tried to put isDataAvailable = GetInternetAvailibility() statement in postDelayed of handler but it is causing enableInternet() disableInternet() to execute at the same time while isDataAvailable = GetInternetAvailibility() gets executed after delay.

I can see from logs, that enableInternet() executes for UserChoice number of times without any delay.

Thread.sleep(10000) just freezes the UI for 10 seconds... How do I achieve this?

EDIT : Let me clear :

public void onClick(View v) {
     // Perform action on click
    for(i=0; i<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);
             }
      });
}

Now whenever I click button I can see in logs that System.out prints message as:

Before
after
Before
after
Before
after
XXX
XXX
XXX

But I want:
Before
XXX
After.
Before
XXX
After.
Before
XXX
After.

Answer

vipul mittal picture vipul mittal · Jan 27, 2014

try this:

public void check() {
    isDataAvailable = GetInternetAvailibility()
    if (!isDataAvailable) {
        disableInternet();
        enableInternet();
        if (retry > 0) {
            retry--;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    check();
                }
            }, 10000);
        }
    }
}