Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 26  Loopers, Handlers, and HandlerThread


Multiple Handlers can be attached to one Looper (Figure 26.5). This means that your Handler’s
Messages may be living side by side with another Handler’s messages.


Figure 26.5  Multiple Handlers, one Looper


Using handlers


Usually, you do not set a message’s target Handler by hand. It is better to build the message by calling
Handler.obtainMessage(...). You pass the other message fields into this method, and it automatically
sets the target to the Handler object the method was called on for you.


Handler.obtainMessage(...) pulls from a common recycling pool to avoid creating new Message
objects, so it is also more efficient than creating new instances.


Once you have obtained a Message, you call sendToTarget() to send the Message to its Handler. The
Handler will then put the Message on the end of Looper’s message queue.


In this case, you are going to obtain a message and send it to its target within the implementation
of queueThumbnail(). The message’s what will be a constant defined as MESSAGE_DOWNLOAD. The
message’s obj will be an object of type T, which will be used to identify the download. In this case,
obj will be the PhotoHolder that the adapter passed in to queueThumbnail().


When the looper pulls a Message from the queue, it gives the message to the message’s
target Handler to handle. Typically, the message is handled in the target’s implementation of
Handler.handleMessage(...).

Free download pdf