Android sleep() without blocking UI

Pascal Ackermann picture Pascal Ackermann · Mar 22, 2015 · Viewed 16k times · Source

For my new Android application I need a function, that timeout my application for 3 Seconds. I tried the function "sleep()" like this:

seekBar1.setProgress(50);                // Set something for my SeekBar

try{
   Thread.sleep(3000);                   // Wait for 3 Seconds
} catch (Exception e){
   System.out.println("Error: "+e);      // Catch the exception
}

button.setEnabled(true);                 // Enable my button

It seems to work, but if I was running the application it does it like this: Wait for 3 Seconds, set progress and enable button. I want first to set the progress and then wait for 3 seconds and only then to enable the button.

Is "sleep()" for the right for my use or what can I do else that my application does it in the right order?

Answer

Mohammad Arman picture Mohammad Arman · Mar 22, 2015

You can use postDelayed() method like this:

handler=new Handler();
Runnable r=new Runnable() {
    public void run() {
        //what ever you do here will be done after 3 seconds delay.              
    }
};
handler.postDelayed(r, 3000);