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?
Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With