I'm new to Android development. There seem to be 2 important classes when dealing with threading in Android: Looper
and Handler
. There are static Looper.myLooper()
and Looper.getMainLooper()
methods to get the current thread's looper and the UI thread's looper, respectively. However, there are no such static methods for Handler
. If you want to post to the UI thread, for example, code samples suggest doing this:
new Handler(Looper.getMainLooper()).post(new Runnable() { ...
Why doesn't Handler
expose a cached, static getMainHandler()
method that looks like this? Wouldn't that avoid creating unnecessary garbage?
private static final Handler mainHandler = new Handler(Looper.getMainLooper());
public static Handler getMainHandler() { return mainHandler; }
Each Looper might have many Handlers. So which Handler would you return for the main Looper?
You can add a Handler to a Looper using the code you provided.
The responsibility of a Looper is to pull messages from an associated message queue, find the message's target handler, and dispatch the message to it. The handler will receive the message and execute its handleMessage(Message)
callback where custom message-handling logic is specified.
To post a message to the message queue, you call Handler.sendMessage()
or, similarly, Handler.post(Runnable)
, which uses messages internally. sendMessage()
is defined on Handler instead of, say, Looper, because in this way the Message's target can be set to the specified Handler. Therefore, when the Looper receives the message, it knows what specific handleMessage
of what specific Handler to run.
Finally, let's say you have a static method that returns the "main" Handler, for example, the Handler used by the system to handle things like configuration changes. That would be quite dangerous as you could call handleMessage()
yourself and trigger logic that should be triggered only by the system.