What is the difference between View.postDelayed() and Handler.postDelayed() on the main thread?

末鹿安然 提交于 2019-11-29 17:26:18

问题


According to the documentation of 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.

On the other hand 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.

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?

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.

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

回答1:


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

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



来源:https://stackoverflow.com/questions/41728973/what-is-the-difference-between-view-postdelayed-and-handler-postdelayed-on-t

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