Android sleep() without blocking UI-ThrowExceptions

Exception or error:

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?

How to solve:

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

###

You shouldn’t ever block the ui thread with a sleep. Its ok to sleep on another thread, but even then it should be avoided. The right way to do this is to post a Runnable to a Handler. Then put whatever code you want to run after the delay in the run() method of the Runnable.

###

You can define a Handle in your Activity and use Handle.postDelayed() from Activity’s onCreate()so you receive a message on that handle in 3 seconds. Upon receving you can enable the button.

You can do the same using AsyncTask where in doInBackground() you just sleep for 3 sec. Then in onPostExecute() you enable the button.

###

Use object of Handler class and use method handler.postDelayed(thread,time).Don’t use sleep() it will block ui thread.

Leave a Reply

Your email address will not be published. Required fields are marked *