Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android sleep() without blocking UI

Tags:

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?

like image 916
Pascal Avatar asked Mar 22 '15 18:03

Pascal


People also ask

Why you shouldn t use thread sleep?

Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.

Is thread sleep blocking?

Sleep method. Calling the Thread. Sleep method causes the current thread to immediately block for the number of milliseconds or the time interval you pass to the method, and yields the remainder of its time slice to another thread. Once that interval elapses, the sleeping thread resumes execution.

How to sleep UI thread in android?

Thread. sleep(time) will causes the thread which sent this message to sleep for the given interval of time. So if you call it in UI thread, it will affect the UI thread. As far as android is concerned it is not advised to obstruct UI thread in any way, otherwise it will result in ANR - application not responding.

Is it a good practice to use thread sleep?

Using Thread. sleep() frequently in an automation framework is not a good practice. If the applied sleep is of 5 secs and the web element is displayed in 2 secs only, the extra 3 secs will increase the execution time. And if you use it more often in the framework, the execution time would increase drastically.


2 Answers

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); 
like image 113
Mohammad Arman Avatar answered Sep 18 '22 15:09

Mohammad Arman


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.

like image 34
Gabe Sechan Avatar answered Sep 19 '22 15:09

Gabe Sechan