编程语言
首页 > 编程语言> > java – 主线程上的View.postDelayed()和Handler.postDelayed()有什么区别?

java – 主线程上的View.postDelayed()和Handler.postDelayed()有什么区别?

作者:互联网

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

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

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.

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

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

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

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(),因此没有区别.

foo()可能会泄漏Activity,你应该使用View.removeCallbacks()来最小化这个机会.

标签:android-handler,android,java,multithreading
来源: https://codeday.me/bug/20191005/1857634.html