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

(gtxtreme123) #1
Passing handlers

Next, modify PhotoGalleryFragment to pass a Handler attached to the main thread to
ThumbnailDownloader. Also, set a ThumbnailDownloadListener to handle the downloaded image
once it is complete.


Listing 26.11  Hooking up to response Handler (PhotoGalleryFragment.java)


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
new FetchItemsTask().execute();


Handler responseHandler = new Handler();
mThumbnailDownloader = new ThumbnailDownloader<>(responseHandler);
mThumbnailDownloader.setThumbnailDownloadListener(
new ThumbnailDownloader.ThumbnailDownloadListener() {
@Override
public void onThumbnailDownloaded(PhotoHolder photoHolder,
Bitmap bitmap) {
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
photoHolder.bindDrawable(drawable);
}
}
);
mThumbnailDownloader.start();
mThumbnailDownloader.getLooper();
Log.i(TAG, "Background thread started");
}


Remember that by default, the Handler will attach itself to the Looper for the current thread. Because
this Handler is created in onCreate(...), it will be attached to the main thread’s Looper.


Now ThumbnailDownloader has access via mResponseHandler to a Handler that is tied to the main
thread’s Looper. It also has your ThumbnailDownloadListener to do the UI work with the returning
Bitmaps. Specifically, the onThumbnailDownloaded implementation sets the Drawable of the originally
requested PhotoHolder to the newly downloaded Bitmap.


You could send a custom Message back to the main thread requesting to add the image to the UI,
similar to how you queued a request on the background thread to download the image. However, this
would require another subclass of Handler, with an override of handleMessage(...).


Instead, let’s use another handy Handler method – post(Runnable).


Handler.post(Runnable) is a convenience method for posting Messages that look like this:


Runnable myRunnable = new Runnable() {
@Override
public void run() {
/ Your code here /
}
};
Message m = mHandler.obtainMessage();
m.callback = myRunnable;


When a Message has its callback field set, it is not routed to its target Handler when pulled off the
message queue. Instead, the run() method of the Runnable stored in callback is executed directly.

Free download pdf