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(); } }
postDelayed(Runnable r, Object token, long delayMillis) Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. final void. removeCallbacks(Runnable r) Remove any pending posts of Runnable r that are in the message queue.
The postDelayed method takes two parameters Runnable and delayMillis . It adds the Runnable to the thread's message queue to be run after the specified amount of time elapses. The Runnable will execute on the thread to which this handler is attached.
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue.
In android Handler is mainly used to update the main thread from background thread or other than main thread. There are two methods are in handler. Post() − it going to post message from background thread to main thread using looper.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With