Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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();     } } 
like image 973
Doron Yakovlev Golani Avatar asked Jan 18 '17 20:01

Doron Yakovlev Golani


People also ask

What is Handler postDelayed?

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.

How do you use kotlin handler postDelayed?

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.

What is Handler and runnable in Android?

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.

What may the handler class be used for?

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.


1 Answers

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.

like image 84
Steve M Avatar answered Sep 30 '22 12:09

Steve M