How can I wait for 10 second without locking application UI in android

137,563

Solution 1

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

Solution 2

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);

Solution 3

1with handler:

handler.sendEmptyMessageDelayed(1, 10000);
}

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        if (msg.what == 1) {
           //your code
        }
    }
};

Solution 4

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();
Share:
137,563
DarkVision
Author by

DarkVision

simple developer like to learn

Updated on July 19, 2022

Comments

  • DarkVision
    DarkVision almost 2 years

    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();
       }
    
  • DarkVision
    DarkVision almost 11 years
    what is the "TRIGGER" because android documentation ask for a int could not put string
  • Anton Bevza
    Anton Bevza almost 11 years
    I was wrong... this is id of your message. Try with 1
  • user3833732
    user3833732 over 7 years
    Easy, and worked without any extra effort. I needed something concize and it worked like a charm
  • Joshua Pinter
    Joshua Pinter over 2 years
    Beauty!!! Worked like a charm. Thanks!