问题
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