concept Handler in category android

appears as: Hdler, Hdler, Handler, The Hdler
Android in Action, Third Edition

This is an excerpt from Manning's book Android in Action, Third Edition.

3.2.3. Multitasking with Handler and Message

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.

Listing 11.10. The Handler Wind and Waves uses to add overlays to the MapView
Android in Practice

This is an excerpt from Manning's book Android in Practice.

Listing 5.16. Using a Timer and a Handler to schedule Services (DON’T DO THIS!)

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.

Listing 5.16. Using a Timer and a Handler to schedule Services (DON’T DO THIS!)

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.

Figure 6.6. Using Message and Handler, we can bind a Handler instance to the UI thread and send messages to it from another thread. Any kind of data can be exchanged that way, without manual synchronization.
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest