Android 2.2:如何编写一个帮助方法来让您的应用程序“睡眠”? N 毫秒?

发布于 2024-10-05 04:16:03 字数 97 浏览 0 评论 0原文

我需要编写一个辅助方法,我可以在应用程序的各个位置使用该方法,以使其“睡眠”N 毫秒。看起来 Handler.postAtTime 可能是一种方法,但我想要任何代码片段如果有的话。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

长不大的小祸害 2024-10-12 04:16:03

您没有说明为什么需要您的应用程序“睡眠”。

假设您需要在一段时间后运行任务:

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

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
沧笙踏歌 2024-10-12 04:16:03

如果您不介意阻塞线程,则可以使用 SystemClock.sleep() 来替代 Thread.sleep()。

好处是它是一句单行话,因为它忽略了
InterruptedException 所以你不需要处理它。

更多信息请参阅http://developer.android.com/reference/android/os/ SystemClock.html

如前所述,您应该避免在主 UI 线程上调用此函数,因为这会导致您的应用程序变得无响应,并可能显示我们都讨厌看到的可怕对话框(请等待或强制关闭。)

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

‘画卷フ 2024-10-12 04:16:03

您在寻找这样的东西吗?

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

}

这将使您调用它的线程休眠指定的时间。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文