43

I am stuck with a problem, I want to wait 10 second because I want my application to start the code below after that 10 sec but without stopping that person from clicking anything else in the application (without calling Thread.sleep();).

try {
    Log.v("msg", "WAIT CheckFrequencyRun");
    Thread.sleep(10000); // giving time to connect to wifi
    
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   //if no network
   if(wifiManager.getConnectionInfo().getNetworkId()==-1){
    //stop wifi
    wifiManager.setWifiEnabled(false);
    Log.v("msg", "no connection");
    handler.postDelayed(this, checkInterval);
   }
   //else connection
   else{
    Log.v("msg", "connection");
    onDestroy();
   }
SiHa
  • 7,830
  • 13
  • 34
  • 43
DarkVision
  • 1,373
  • 3
  • 20
  • 33
  • postDelayed wont't lock your Ui but Thread.Sleep do. Remove Thread.Sleep and continue your work in your Runnable – Mohsen Afshin Jun 21 '13 at 14:11
  • Have a look at these questions, they're looking quite similiar: - https://stackoverflow.com/questions/4111905/how-do-you-have-the-code-pause-for-a-couple-of-seconds-in-android?rq=1 - https://stackoverflow.com/questions/9630681/android-wait-the-main-thread-while-a-dialog-gets-input-in-a-separate-thread?rq=1 - https://stackoverflow.com/questions/9640880/android-waiting-for-an-action?rq=1 - https://stackoverflow.com/questions/13765034/wait-a-time-android?rq=1 – Marvin Emil Brach Jun 21 '13 at 14:08

4 Answers4

182

You can use this:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
     // Actions to do after 10 seconds
    }
}, 10000);

For Stop the Handler, You can try this: handler.removeCallbacksAndMessages(null);

abdullahselek
  • 7,893
  • 3
  • 50
  • 40
Recaldev
  • 2,836
  • 3
  • 14
  • 6
20

You never want to call thread.sleep() on the UI thread as it sounds like you have figured out. This freezes the UI and is always a bad thing to do. You can use a separate Thread and postDelayed

This SO answer shows how to do that as well as several other options

Handler

TimerTask

You can look at these and see which will work best for your particular situation

Community
  • 1
  • 1
codeMagic
  • 44,549
  • 13
  • 77
  • 93
3

1with handler:

handler.sendEmptyMessageDelayed(1, 10000);
}

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        if (msg.what == 1) {
           //your code
        }
    }
};
Anton Bevza
  • 463
  • 7
  • 18
2

do this on a new thread (seperate it from main thread)

 new Thread(new Runnable() {
     @Override
     public void run() {
        // TODO Auto-generated method stub
     }
}).run();
Marcis
  • 71
  • 6