Android 2.2: How can you write a helper method to have your app 'sleep' for N milliseconds?

狂风中的少年 提交于 2019-12-13 06:41:46

问题


I need to write a helper method which I can use in various places in the app to essentially make it 'sleep' for N milliseconds.It looks like Handler.postAtTime may be one way to do it, but I'd like any code snippets if available.


回答1:


Are you looking for something like this?

try {
  //Put the thread to sleep for the desired amount of time (milliseconds)
  Thread.currentThread().sleep(1000);
}
catch(InterruptedException ie){

}

This will put the thread you are calling it from to sleep for the amount of time you specify.




回答2:


You did not say why you need your app to "sleep".

Assuming you need to run a task after some time:

Handler h = new Handler();
h.postDelayed(new Runnable() {
    public void run() {
       // do something here
    }
}, 1000); // 1000 ms delay



回答3:


If you don't mind blocking the thread, an alternative to Thread.sleep() is SystemClock.sleep().

Benefit is that it's a one-liner, as it ignores the InterruptedException so you don't need to handle it.

More info on http://developer.android.com/reference/android/os/SystemClock.html.

As already stated, you should avoid calling this on the main UI thread as it will cause your app to become unresponsive and potentially show the dreaded dialog we all hate to see (please wait or force close.)



来源:https://stackoverflow.com/questions/4304466/android-2-2-how-can-you-write-a-helper-method-to-have-your-app-sleep-for-n-mi

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