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


You implemented Handler.handleMessage(...) in your Handler subclass within onLooperPrepared().
HandlerThread.onLooperPrepared() is called before the Looper checks the queue for the first time.
This makes it a good place to create your Handler implementation.


Within Handler.handleMessage(...), you check the message type, retrieve the obj value (which will
be of type T and serves as the identifier for the request), and then pass it to handleRequest(...). (Recall
that Handler.handleMessage(...) will get called when a download message is pulled off the queue and
ready to be processed.)


The handleRequest() method is a helper method where the downloading happens. Here you check for
the existence of a URL. Then you pass the URL to a new instance of your old friend FlickrFetchr. In
particular, you use the FlickrFetchr.getUrlBytes(...) method that you created with such foresight in
the last chapter.


Finally, you use BitmapFactory to construct a bitmap with the array of bytes returned from
getUrlBytes(...).


Run PhotoGallery and check Logcat for your confirming log statements.


Of course, the request will not be completely handled until you set the bitmap on the PhotoHolder that
originally came from PhotoAdapter. However, this is UI work, so it must be done on the main thread.


Everything you have seen so far uses handlers and messages on a single thread –
ThumbnailDownloader putting messages in ThumbnailDownloader’s own inbox. In the next section,
you will see how ThumbnailDownloader can use a Handler to post requests to a separate thread
(namely, the main thread).


Passing handlers


So far you are able to schedule work on the background thread from the main thread using
ThumbnailDownloader’s mRequestHandler. This flow is shown in Figure 26.7.


Figure 26.7  Scheduling work on ThumbnailDownloader from the main thread

Free download pdf