主线程上的View.postDelayed()和Handler.postDelayed()有什么区别? [英] What is the difference between View.postDelayed() and Handler.postDelayed() on the main thread?

查看:2941
本文介绍了主线程上的View.postDelayed()和Handler.postDelayed()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Handler.postDelayed(Runnable r,long delayMillis)的文档


使Runnable r添加到消息队列中,在指定的时间量过后运行
。 runnable将在附加此处理程序的线程上运行

Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the thread to which this handler is attached.

另一方面 View.postDelayed(Runnable action,long delayMillis)


使Runnable被添加到消息队列,在
之后运行指定的时间量。 runnable将在
用户界面线程上运行。

Causes the Runnable to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the user interface thread.

我想知道两者之间是否存在差异从主线程调用它们时,特别是,如果活动被销毁时存在差异?

I want to know if there is a difference between the two while calling them from the main thread and in particular, if there is a difference when the activity is being destroyed?

我已经读过这个文章关于当我使用内部类Handler和我时如何泄漏Activity想知道是否使用 View.postDelayed()会导致同样的问题。

I have read this article about how I might leak an Activity when I use an inner class Handler and I was wondering whether using View.postDelayed() would cause the same problem.

例如foo()可能导致一个问题或活动的破坏是否会解决 Runnable 匿名类持有对活动的引用这一事实?

For example could foo() cause an issue or would the destruction of the activity solve the fact that the Runnable anonymous class is holding a reference to the activity?

public class MyActiviy extends Activity {
    private void foo(View v) {
        v.postDelayed(new Runnable() {
            public void run() {
                // some delayed work
            }
        }, 60000);
        finish();
    }
}


推荐答案

来自源, View.postDelayed()只是在内部处理程序上使用 Handler.postDelayed(),所以没有区别。

From the source, View.postDelayed() is simply using Handler.postDelayed() on an internal handler so there is no difference.

foo()可能会泄漏活动,你应该使用 View.removeCallbacks() 尽量减少这种机会。

foo() may leak the Activity, you should use View.removeCallbacks() to minimize this chance.

这篇关于主线程上的View.postDelayed()和Handler.postDelayed()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆