Handler

public class Handler
extends Object

java.lang.Object
   ↳ android.os.Handler


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. When you create a new Handler it is bound to a Looper. It will deliver messages and runnables to that Looper's message queue and execute them on that Looper's thread.

There are two main uses for a Handler: (1) to schedule messages and runnables to be executed at some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.

Scheduling messages is accomplished with the post(Runnable), postAtTime(java.lang.Runnable, long), postDelayed(Runnable, Object, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long) methods. The post versions allow you to enqueue Runnable objects to be called by the message queue when they are received; the sendMessage versions allow you to enqueue a Message object containing a bundle of data that will be processed by the Handler's handleMessage(Message) method (requiring that you implement a subclass of Handler).

When posting or sending to a Handler, you can either allow the item to be processed as soon as the message queue is ready to do so, or specify a delay before it gets processed or absolute time for it to be processed. The latter two allow you to implement timeouts, ticks, and other timing-based behavior.

When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create. You can create your own threads, and communicate back with the main application thread through a Handler. This is done by calling the same post or sendMessage methods as before, but from your new thread. The given Runnable or Message will then be scheduled in the Handler's message queue and processed when appropriate.

Summary

Nested classes

interface Handler.Callback

Callback interface you can use when instantiating a Handler to avoid having to implement your own subclass of Handler. 

Public constructors

Handler()

This constructor is deprecated. Implicitly choosing a Looper during Handler construction can lead to bugs where operations are silently lost (if the Handler is not expecting new tasks and quits), crashes (if a handler is sometimes created on a thread without a Looper active), or race conditions, where the thread a handler is associated with is not what the author anticipated. Instead, use an Executor or specify the Looper explicitly, using Looper#getMainLooper, View.getHandler(), or similar. If the implicit thread local behavior is required for compatibility, use new Handler(Looper.myLooper()) to make it clear to readers.

Handler(Handler.Callback callback)

This constructor is deprecated. Implicitly choosing a Looper during Handler construction can lead to bugs where operations are silently lost (if the Handler is not expecting new tasks and quits), crashes (if a handler is sometimes created on a thread without a Looper active), or race conditions, where the thread a handler is associated with is not what the author anticipated. Instead, use an Executor or specify the Looper explicitly, using Looper#getMainLooper, View.getHandler(), or similar. If the implicit thread local behavior is required for compatibility, use new Handler(Looper.myLooper(), callback) to make it clear to readers.

Handler(Looper looper)

Use the provided Looper instead of the default one.

Handler(Looper looper, Handler.Callback callback)

Use the provided Looper instead of the default one and take a callback interface in which to handle messages.

Public methods

static Handler createAsync(Looper looper, Handler.Callback callback)

Create a new Handler whose posted messages and runnables are not subject to synchronization barriers such as display vsync.

static Handler createAsync(Looper looper)

Create a new Handler whose posted messages and runnables are not subject to synchronization barriers such as display vsync.

void dispatchMessage(Message msg)

Handle system messages here.

final void dump(Printer pw, String prefix)
final Looper getLooper()
String getMessageName(Message message)

Returns a string representing the name of the specified message.

void handleMessage(Message msg)

Subclasses must implement this to receive messages.

final boolean hasCallbacks(Runnable r)

Check if there are any pending posts of messages with callback r in the message queue.

final boolean hasMessages(int what)

Check if there are any pending posts of messages with code 'what' in the message queue.

final boolean hasMessages(int what, Object object)

Check if there are any pending posts of messages with code 'what' and whose obj is 'object' in the message queue.

final Message obtainMessage(int what, Object obj)

Same as obtainMessage(), except that it also sets the what and obj members of the returned Message.

final Message obtainMessage()

Returns a new Message from the global message pool.

final Message obtainMessage(int what, int arg1, int arg2)

Same as obtainMessage(), except that it also sets the what, arg1 and arg2 members of the returned Message.

final Message obtainMessage(int what, int arg1, int arg2, Object obj)

Same as obtainMessage(), except that it also sets the what, obj, arg1,and arg2 values on the returned Message.

final Message obtainMessage(int what)

Same as obtainMessage(), except that it also sets the what member of the returned Message.

final boolean post(Runnable r)

Causes the Runnable r to be added to the message queue.

final boolean postAtFrontOfQueue(Runnable r)

Posts a message to an object that implements Runnable.

final boolean postAtTime(Runnable r, long uptimeMillis)

Causes the Runnable r to be added to the message queue, to be run at a specific time given by uptimeMillis.

final boolean postAtTime(Runnable r, Object token, long uptimeMillis)

Causes the Runnable r to be added to the message queue, to be run at a specific time given by uptimeMillis.

final boolean 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.

final boolean 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.

final void removeCallbacks(Runnable r, Object token)

Remove any pending posts of Runnable r with Object token that are in the message queue.

final void removeCallbacksAndMessages(Object token)

Remove any pending posts of callbacks and sent messages whose obj is token.

final void removeMessages(int what)

Remove any pending posts of messages with code 'what' that are in the message queue.

final void removeMessages(int what, Object object)

Remove any pending posts of messages with code 'what' and whose obj is 'object' that are in the message queue.

final boolean sendEmptyMessage(int what)

Sends a Message containing only the what value.

final boolean sendEmptyMessageAtTime(int what, long uptimeMillis)

Sends a Message containing only the what value, to be delivered at a specific time.

final boolean sendEmptyMessageDelayed(int what, long delayMillis)

Sends a Message containing only the what value, to be delivered after the specified amount of time elapses.

final boolean sendMessage(Message msg)

Pushes a message onto the end of the message queue after all pending messages before the current time.

final boolean sendMessageAtFrontOfQueue(Message msg)

Enqueue a message at the front of the message queue, to be processed on the next iteration of the message loop.

boolean sendMessageAtTime(Message msg, long uptimeMillis)

Enqueue a message into the message queue after all pending messages before the absolute time (in milliseconds) uptimeMillis.

final boolean sendMessageDelayed(Message msg, long delayMillis)

Enqueue a message into the message queue after all pending messages before (current time + delayMillis).

String toString()

Returns a string representation of the object.

Inherited methods

Public constructors

Handler

Added in API level 1
public Handler ()

This constructor is deprecated.
Implicitly choosing a Looper during Handler construction can lead to bugs where operations are silently lost (if the Handler is not expecting new tasks and quits), crashes (if a handler is sometimes created on a thread without a Looper active), or race conditions, where the thread a handler is associated with is not what the author anticipated. Instead, use an Executor or specify the Looper explicitly, using Looper#getMainLooper, View.getHandler(), or similar. If the implicit thread local behavior is required for compatibility, use new Handler(Looper.myLooper()) to make it clear to readers.

Default constructor associates this handler with the Looper for the current thread. If this thread does not have a looper, this handler won't be able to receive messages so an exception is thrown.

Handler

Added in API level 1
public Handler (Handler.Callback callback)

This constructor is deprecated.
Implicitly choosing a Looper during Handler construction can lead to bugs where operations are silently lost (if the Handler is not expecting new tasks and quits), crashes (if a handler is sometimes created on a thread without a Looper active), or race conditions, where the thread a handler is associated with is not what the author anticipated. Instead, use an Executor or specify the Looper explicitly, using Looper#getMainLooper, View.getHandler(), or similar. If the implicit thread local behavior is required for compatibility, use new Handler(Looper.myLooper(), callback) to make it clear to readers.

Constructor associates this handler with the Looper for the current thread and takes a callback interface in which you can handle messages. If this thread does not have a looper, this handler won't be able to receive messages so an exception is thrown.

Parameters
callback Handler.Callback: The callback interface in which to handle messages, or null.

Handler

Added in API level 1
public Handler (Looper looper)

Use the provided Looper instead of the default one.

Parameters
looper Looper: The looper, must not be null.

Handler

Added in API level 1
public Handler (Looper looper, 
                Handler.Callback callback)

Use the provided Looper instead of the default one and take a callback interface in which to handle messages.

Parameters
looper Looper: The looper, must not be null.

callback Handler.Callback: The callback interface in which to handle messages, or null.

Public methods

createAsync

Added in API level 28
public static Handler createAsync (Looper looper, 
                Handler.Callback callback)

Create a new Handler whose posted messages and runnables are not subject to synchronization barriers such as display vsync.

Messages sent to an async handler are guaranteed to be ordered with respect to one another, but not necessarily with respect to messages from other Handlers.

Parameters
looper Looper: the Looper that the new Handler should be bound to This value cannot be null.

callback Handler.Callback: This value cannot be null.

Returns
Handler a new async Handler instance This value cannot be null.

createAsync

Added in API level 28
public static Handler createAsync (Looper looper)

Create a new Handler whose posted messages and runnables are not subject to synchronization barriers such as display vsync.

Messages sent to an async handler are guaranteed to be ordered with respect to one another, but not necessarily with respect to messages from other Handlers.

Parameters
looper Looper: the Looper that the new Handler should be bound to This value cannot be null.

Returns
Handler a new async Handler instance This value cannot be null.

dispatchMessage

Added in API level 1
public void dispatchMessage (Message msg)

Handle system messages here.

Parameters
msg Message: This value cannot be null.

dump

Added in API level 1
public final void dump (Printer pw, 
                String prefix)

Parameters
pw Printer: This value cannot be null.

prefix String: This value cannot be null.

getLooper

Added in API level 1
public final Looper getLooper ()

Returns
Looper This value cannot be null.

getMessageName

Added in API level 14
public String getMessageName (Message message)

Returns a string representing the name of the specified message. The default implementation will either return the class name of the message callback if any, or the hexadecimal representation of the message "what" field.

Parameters
message Message: The message whose name is being queried This value cannot be null.

Returns
String This value cannot be null.

handleMessage

Added in API level 1
public void handleMessage (Message msg)

Subclasses must implement this to receive messages.

Parameters
msg Message: This value cannot be null.

hasCallbacks

Added in API level 29
public final boolean hasCallbacks (Runnable r)

Check if there are any pending posts of messages with callback r in the message queue.

Parameters
r Runnable: This value cannot be null.

Returns
boolean

hasMessages

Added in API level 1
public final boolean hasMessages (int what)

Check if there are any pending posts of messages with code 'what' in the message queue.

Parameters
what int

Returns
boolean

hasMessages

Added in API level 1
public final boolean hasMessages (int what, 
                Object object)

Check if there are any pending posts of messages with code 'what' and whose obj is 'object' in the message queue.

Parameters
what int

object Object: This value may be null.

Returns
boolean

obtainMessage

Added in API level 1
public final Message obtainMessage (int what, 
                Object obj)

Same as obtainMessage(), except that it also sets the what and obj members of the returned Message.

Parameters
what int: Value to assign to the returned Message.what field.

obj Object: Value to assign to the returned Message.obj field. This value may be null.

Returns
Message A Message from the global message pool. This value cannot be null.

obtainMessage

Added in API level 1
public final Message obtainMessage ()

Returns a new Message from the global message pool. More efficient than creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this). If you don't want that facility, just call Message.obtain() instead.

Returns
Message This value cannot be null.

obtainMessage

Added in API level 1
public final Message obtainMessage (int what, 
                int arg1, 
                int arg2)

Same as obtainMessage(), except that it also sets the what, arg1 and arg2 members of the returned Message.

Parameters
what int: Value to assign to the returned Message.what field.

arg1 int: Value to assign to the returned Message.arg1 field.

arg2 int: Value to assign to the returned Message.arg2 field.

Returns
Message A Message from the global message pool. This value cannot be null.

obtainMessage

Added in API level 1
public final Message obtainMessage (int what, 
                int arg1, 
                int arg2, 
                Object obj)

Same as obtainMessage(), except that it also sets the what, obj, arg1,and arg2 values on the returned Message.

Parameters
what int: Value to assign to the returned Message.what field.

arg1 int: Value to assign to the returned Message.arg1 field.

arg2 int: Value to assign to the returned Message.arg2 field.

obj Object: Value to assign to the returned Message.obj field. This value may be null.

Returns
Message A Message from the global message pool. This value cannot be null.

obtainMessage

Added in API level 1
public final Message obtainMessage (int what)

Same as obtainMessage(), except that it also sets the what member of the returned Message.

Parameters
what int: Value to assign to the returned Message.what field.

Returns
Message A Message from the global message pool. This value cannot be null.

post

Added in API level 1
public final boolean post (Runnable r)

Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.

Parameters
r Runnable: The Runnable that will be executed. This value cannot be null.

Returns
boolean Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

postAtFrontOfQueue

Added in API level 1
public final boolean postAtFrontOfQueue (Runnable r)

Posts a message to an object that implements Runnable. Causes the Runnable r to executed on the next iteration through the message queue. The runnable will be run on the thread to which this handler is attached. This method is only for use in very special circumstances -- it can easily starve the message queue, cause ordering problems, or have other unexpected side-effects.

Parameters
r Runnable: The Runnable that will be executed. This value cannot be null.

Returns
boolean Returns true if the message was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

postAtTime

Added in API level 1
public final boolean postAtTime (Runnable r, 
                long uptimeMillis)

Causes the Runnable r to be added to the message queue, to be run at a specific time given by uptimeMillis. The time-base is SystemClock.uptimeMillis(). Time spent in deep sleep will add an additional delay to execution. The runnable will be run on the thread to which this handler is attached.

Parameters
r Runnable: The Runnable that will be executed. This value cannot be null.

uptimeMillis long: The absolute time at which the callback should run, using the SystemClock.uptimeMillis() time-base.

Returns
boolean Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped.

postAtTime

Added in API level 1
public final boolean postAtTime (Runnable r, 
                Object token, 
                long uptimeMillis)

Causes the Runnable r to be added to the message queue, to be run at a specific time given by uptimeMillis. The time-base is SystemClock.uptimeMillis(). Time spent in deep sleep will add an additional delay to execution. The runnable will be run on the thread to which this handler is attached.

Parameters
r Runnable: The Runnable that will be executed. This value cannot be null.

token Object: An instance which can be used to cancel r via removeCallbacksAndMessages(Object). This value may be null.

uptimeMillis long: The absolute time at which the callback should run, using the SystemClock.uptimeMillis() time-base.

Returns
boolean Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped.

postDelayed

Added in API level 1
public final boolean 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. The time-base is SystemClock.uptimeMillis(). Time spent in deep sleep will add an additional delay to execution.

Parameters
r Runnable: The Runnable that will be executed. This value cannot be null.

delayMillis long: The delay (in milliseconds) until the Runnable will be executed.

Returns
boolean Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped.

postDelayed

Added in API level 28
public final boolean 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. The runnable will be run on the thread to which this handler is attached. The time-base is SystemClock.uptimeMillis(). Time spent in deep sleep will add an additional delay to execution.

Parameters
r Runnable: The Runnable that will be executed. This value cannot be null.

token Object: An instance which can be used to cancel r via removeCallbacksAndMessages(Object). This value may be null.

delayMillis long: The delay (in milliseconds) until the Runnable will be executed.

Returns
boolean Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped.

removeCallbacks

Added in API level 1
public final void removeCallbacks (Runnable r)

Remove any pending posts of Runnable r that are in the message queue.

Parameters
r Runnable: This value cannot be null.

removeCallbacks

Added in API level 1
public final void removeCallbacks (Runnable r, 
                Object token)

Remove any pending posts of Runnable r with Object token that are in the message queue. If token is null, all callbacks will be removed.

Parameters
r Runnable: This value cannot be null.

token Object: This value may be null.

removeCallbacksAndMessages

Added in API level 1
public final void removeCallbacksAndMessages (Object token)

Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

Parameters
token Object: This value may be null.

removeMessages

Added in API level 1
public final void removeMessages (int what)

Remove any pending posts of messages with code 'what' that are in the message queue.

Parameters
what int

removeMessages

Added in API level 1
public final void removeMessages (int what, 
                Object object)

Remove any pending posts of messages with code 'what' and whose obj is 'object' that are in the message queue. If object is null, all messages will be removed.

Parameters
what int

object Object: This value may be null.

sendEmptyMessage

Added in API level 1
public final boolean sendEmptyMessage (int what)

Sends a Message containing only the what value.

Parameters
what int

Returns
boolean Returns true if the message was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

sendEmptyMessageAtTime

Added in API level 1
public final boolean sendEmptyMessageAtTime (int what, 
                long uptimeMillis)

Sends a Message containing only the what value, to be delivered at a specific time.

Parameters
what int

uptimeMillis long

Returns
boolean Returns true if the message was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

sendEmptyMessageDelayed

Added in API level 1
public final boolean sendEmptyMessageDelayed (int what, 
                long delayMillis)

Sends a Message containing only the what value, to be delivered after the specified amount of time elapses.

Parameters
what int

delayMillis long

Returns
boolean Returns true if the message was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

sendMessage

Added in API level 1
public final boolean sendMessage (Message msg)

Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received in handleMessage(Message), in the thread attached to this handler.

Parameters
msg Message: This value cannot be null.

Returns
boolean Returns true if the message was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

sendMessageAtFrontOfQueue

Added in API level 1
public final boolean sendMessageAtFrontOfQueue (Message msg)

Enqueue a message at the front of the message queue, to be processed on the next iteration of the message loop. You will receive it in handleMessage(Message), in the thread attached to this handler. This method is only for use in very special circumstances -- it can easily starve the message queue, cause ordering problems, or have other unexpected side-effects.

Parameters
msg Message: This value cannot be null.

Returns
boolean Returns true if the message was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

sendMessageAtTime

Added in API level 1
public boolean sendMessageAtTime (Message msg, 
                long uptimeMillis)

Enqueue a message into the message queue after all pending messages before the absolute time (in milliseconds) uptimeMillis. The time-base is SystemClock.uptimeMillis(). Time spent in deep sleep will add an additional delay to execution. You will receive it in handleMessage(Message), in the thread attached to this handler.

Parameters
msg Message: This value cannot be null.

uptimeMillis long: The absolute time at which the message should be delivered, using the SystemClock.uptimeMillis() time-base.

Returns
boolean Returns true if the message was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the message will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped.

sendMessageDelayed

Added in API level 1
public final boolean sendMessageDelayed (Message msg, 
                long delayMillis)

Enqueue a message into the message queue after all pending messages before (current time + delayMillis). You will receive it in handleMessage(Message), in the thread attached to this handler.

Parameters
msg Message: This value cannot be null.

delayMillis long

Returns
boolean Returns true if the message was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the message will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped.

toString

Added in API level 1
public String toString ()

Returns a string representation of the object.

Returns
String a string representation of the object.