Android sleep() without blocking UI

99封情书 提交于 2019-11-27 14:40:48

问题


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?


回答1:


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



回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/29198262/android-sleep-without-blocking-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!