concept Handler in category android

This is an excerpt from Manning's book Android in Action, Third Edition.
Handler helps you manage messaging and scheduling operations for Android. This class allows you to queue tasks to be run on different threads and to schedule tasks using Message and Runnable objects.
Figure 3.5. Using the Handler class with separate threads, and the relationship among HandlerThread, Looper, and MessageQueue
![]()
When you’re implementing a handler, you’ll need to provide a handleMessage(Message m) method. When you create a new thread, you can then call one of several sendMessage methods on Handler from within that thread’s run method, as our examples and figure 3.5 demonstrate. Calling sendMessage() puts your message on the MessageQueue, which the Looper services.

This is an excerpt from Manning's book Android in Practice.
Your Service needs to execute code at some point in the future. But even though your Service may be currently running, you can’t guarantee that it’ll still be running at that point. If that was the case—or if it was okay for your code to not execute if your Service isn’t running in the future—then you could use a combination of Java’s Timer and TimerTask along with Android’s Handler. The following listing shows such a naïve implementation.
You could store progress information in a shared variable and access it from both threads: the worker thread writes to it, and the UI thread periodically reads from it. But this would require us to synchronize access to it, which is always cumbersome. It turns out that there’s an easier way to do these things on Android—Android’s message-passing facilities. This approach uses message queues to allow interthread communication in a controlled, thread-safe manner. Progress information can therefore be passed from a worker to the UI thread by posting update messages to the UI thread’s message queue using Android’s Handler and Message classes.