Class Handler

java.lang.Object
icyllis.modernui.core.Handler

public class Handler extends Object
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(java.lang.Runnable), postAtTime(Runnable, long), postDelayed(java.lang.Runnable, long), sendEmptyMessage(int), sendMessage(icyllis.modernui.core.Message), sendMessageAtTime(icyllis.modernui.core.Message, long), and sendMessageDelayed(icyllis.modernui.core.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(icyllis.modernui.core.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.

  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Class
    Description
    static interface 
    Callback interface you can use when instantiating a Handler to avoid having to implement your own subclass of Handler.
  • Constructor Summary

    Constructors
    Constructor
    Description
    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.
  • Method Summary

    Modifier and Type
    Method
    Description
    static Handler
    Create a new Handler whose posted messages and runnables are not subject to synchronization barriers such as display vsync.
    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.
    void
    Handle system messages here.
    Returns a string representing the name of the specified message.
    Returns the MessageQueue object associated with this Handler.
    void
    Subclasses can implement this to receive messages.
    final boolean
    Check if there are any pending posts of messages with callback r in the message queue.
    final boolean
    Return whether there are any messages or callbacks currently scheduled on this handler.
    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 boolean
    Returns whether this handler was queued from the current thread.
    final Message
    Returns a new Message from the global message pool.
    final Message
    obtainMessage(int what)
    Same as obtainMessage(), except that it also sets the what member of the returned Message.
    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, Object obj)
    Same as obtainMessage(), except that it also sets the what and obj members of the returned Message.
    final boolean
    Causes the Runnable r to be added to the message queue.
    final boolean
    Posts a message to an object that implements Runnable.
    final boolean
    postAtTime(Runnable r, long timeMillis)
    Causes the Runnable r to be added to the message queue, to be run at a specific time given by timeMillis.
    final boolean
    postAtTime(Runnable r, Object token, long timeMillis)
    Causes the Runnable r to be added to the message queue, to be run at a specific time given by timeMillis.
    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
    Remove any pending posts of Runnable r that are in the message queue.
    final void
    Remove any pending posts of Runnable r with Object token that are in the message queue.
    final void
    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 timeMillis)
    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
    Pushes a message onto the end of the message queue after all pending messages before the current time.
    final boolean
    Enqueue a message at the front of the message queue, to be processed on the next iteration of the message loop.
    final boolean
    sendMessageAtTime(Message msg, long timeMillis)
    Enqueue a message into the message queue after all pending messages before the absolute time (in milliseconds) timeMillis.
    final boolean
    sendMessageDelayed(Message msg, long delayMillis)
    Enqueue a message into the message queue after all pending messages before (current time + delayMillis).
     

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
  • Constructor Details

    • Handler

      public Handler(Looper looper)
      Use the provided Looper instead of the default one.
      Parameters:
      looper - The looper, must not be null.
    • Handler

      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 - The looper, must not be null.
      callback - The callback interface in which to handle messages.
  • Method Details

    • createAsync

      @NonNull 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 - the Looper that the new Handler should be bound to
      Returns:
      a new async Handler instance
    • createAsync

      @NonNull 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 - the Looper that the new Handler should be bound to
      callback - the callback interface in which to handle messages.
      Returns:
      a new async Handler instance
    • getMessageName

      @NonNull public String getMessageName(@NonNull 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 - The message whose name is being queried
    • obtainMessage

      @NonNull 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).
      Returns:
      A Message from the global message pool.
    • obtainMessage

      @NonNull public final Message obtainMessage(int what)
      Same as obtainMessage(), except that it also sets the what member of the returned Message.
      Parameters:
      what - Value to assign to the returned Message.what field.
      Returns:
      A Message from the global message pool.
    • obtainMessage

      @NonNull public final Message obtainMessage(int what, @Nullable Object obj)
      Same as obtainMessage(), except that it also sets the what and obj members of the returned Message.
      Parameters:
      what - Value to assign to the returned Message.what field.
      obj - Value to assign to the returned Message.obj field.
      Returns:
      A Message from the global message pool.
    • obtainMessage

      @NonNull 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 - Value to assign to the returned Message.what field.
      arg1 - Value to assign to the returned Message.arg1 field.
      arg2 - Value to assign to the returned Message.arg2 field.
      Returns:
      A Message from the global message pool.
    • obtainMessage

      @NonNull public final Message obtainMessage(int what, int arg1, int arg2, @Nullable Object obj)
      Same as obtainMessage(), except that it also sets the what, obj, arg1,and arg2 values on the returned Message.
      Parameters:
      what - Value to assign to the returned Message.what field.
      arg1 - Value to assign to the returned Message.arg1 field.
      arg2 - Value to assign to the returned Message.arg2 field.
      obj - Value to assign to the returned Message.obj field.
      Returns:
      A Message from the global message pool.
    • post

      public final boolean post(@NonNull 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 - The Runnable that will be executed.
      Returns:
      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.
    • postAtTime

      public final boolean postAtTime(@NonNull Runnable r, long timeMillis)
      Causes the Runnable r to be added to the message queue, to be run at a specific time given by timeMillis. The time-base is Core.timeMillis(). Time spent in deep sleep will add a delay to execution. The runnable will be run on the thread to which this handler is attached.
      Parameters:
      r - The Runnable that will be executed.
      timeMillis - The absolute time at which the callback should run, using the Core.timeMillis() time-base.
      Returns:
      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

      public final boolean postAtTime(@NonNull Runnable r, @Nullable Object token, long timeMillis)
      Causes the Runnable r to be added to the message queue, to be run at a specific time given by timeMillis. The time-base is Core.timeMillis(). Time spent in deep sleep will add a delay to execution. The runnable will be run on the thread to which this handler is attached.
      Parameters:
      r - The Runnable that will be executed.
      token - An instance which can be used to cancel r via removeCallbacksAndMessages(java.lang.Object).
      timeMillis - The absolute time at which the callback should run, using the Core.timeMillis() time-base.
      Returns:
      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.
      See Also:
    • postDelayed

      public final boolean postDelayed(@NonNull 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 Core.timeMillis(). Time spent in deep sleep will add a delay to execution.
      Parameters:
      r - The Runnable that will be executed.
      delayMillis - The delay (in milliseconds) until the Runnable will be executed.
      Returns:
      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

      public final boolean postDelayed(@NonNull Runnable r, @Nullable 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 Core.timeMillis(). Time spent in deep sleep will add a delay to execution.
      Parameters:
      r - The Runnable that will be executed.
      token - An instance which can be used to cancel r via removeCallbacksAndMessages(java.lang.Object).
      delayMillis - The delay (in milliseconds) until the Runnable will be executed.
      Returns:
      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.
    • postAtFrontOfQueue

      public final boolean postAtFrontOfQueue(@NonNull 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 - The Runnable that will be executed.
      Returns:
      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.
    • removeCallbacks

      public final void removeCallbacks(@NonNull Runnable r)
      Remove any pending posts of Runnable r that are in the message queue.
    • removeCallbacks

      public final void removeCallbacks(@NonNull Runnable r, @Nullable 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.
    • sendMessage

      public final boolean sendMessage(@NonNull 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(icyllis.modernui.core.Message), in the thread attached to this handler.
      Returns:
      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.
    • sendEmptyMessage

      public final boolean sendEmptyMessage(int what)
      Sends a Message containing only the what value.
      Returns:
      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

      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.
      Returns:
      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.
      See Also:
    • sendEmptyMessageAtTime

      public final boolean sendEmptyMessageAtTime(int what, long timeMillis)
      Sends a Message containing only the what value, to be delivered at a specific time.
      Returns:
      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.
      See Also:
    • sendMessageDelayed

      public final boolean sendMessageDelayed(@NonNull 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(icyllis.modernui.core.Message), in the thread attached to this handler.
      Returns:
      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.
    • sendMessageAtTime

      public final boolean sendMessageAtTime(@NonNull Message msg, long timeMillis)
      Enqueue a message into the message queue after all pending messages before the absolute time (in milliseconds) timeMillis. The time-base is Core.timeMillis(). Time spent in deep sleep will add a delay to execution. You will receive it in handleMessage(icyllis.modernui.core.Message), in the thread attached to this handler.
      Parameters:
      timeMillis - The absolute time at which the message should be delivered, using the Core.timeMillis() time-base.
      Returns:
      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.
    • sendMessageAtFrontOfQueue

      public final boolean sendMessageAtFrontOfQueue(@NonNull 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(icyllis.modernui.core.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.
      Returns:
      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.
    • removeMessages

      public final void removeMessages(int what)
      Remove any pending posts of messages with code 'what' that are in the message queue.
    • removeMessages

      public final void removeMessages(int what, @Nullable 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.
    • removeCallbacksAndMessages

      public final void removeCallbacksAndMessages(@Nullable 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.
    • hasMessages

      public final boolean hasMessages(int what)
      Check if there are any pending posts of messages with code 'what' in the message queue.
    • hasMessages

      public final boolean hasMessages()
      Return whether there are any messages or callbacks currently scheduled on this handler.
    • hasMessages

      public final boolean hasMessages(int what, @Nullable Object object)
      Check if there are any pending posts of messages with code 'what' and whose obj is 'object' in the message queue.
    • hasCallbacks

      public final boolean hasCallbacks(@NonNull Runnable r)
      Check if there are any pending posts of messages with callback r in the message queue.
    • handleMessage

      public void handleMessage(@NonNull Message msg)
      Subclasses can implement this to receive messages.
    • dispatchMessage

      public void dispatchMessage(@NonNull Message msg)
      Handle system messages here.
    • getQueue

      @NonNull public final MessageQueue getQueue()
      Returns the MessageQueue object associated with this Handler.
    • isCurrentThread

      public final boolean isCurrentThread()
      Returns whether this handler was queued from the current thread.
    • toString

      public String toString()
      Overrides:
      toString in class Object