Chapter 26 Loopers, Handlers, and HandlerThread
Finally, within PhotoAdapter.onBindViewHolder(...), call the thread’s queueThumbnail() method and
pass in the target PhotoHolder where the image will ultimately be placed and the GalleryItem’s URL
to download from.
Listing 26.6 Hooking up ThumbnailDownloader
(PhotoGalleryFragment.java)
public class PhotoGalleryFragment extends Fragment {
private class PhotoAdapter extends RecyclerView.Adapter
@Override
public void onBindViewHolder(PhotoHolder photoHolder, int position) {
GalleryItem galleryItem = mGalleryItems.get(position);
Drawable placeholder = getResources().getDrawable(R.drawable.bill_up_close);
photoHolder.bindDrawable(placeholder);
mThumbnailDownloader.queueThumbnail(photoHolder, galleryItem.getUrl());
}
}
}
Run PhotoGallery and check out Logcat. When you scroll around the RecyclerView, you should see
lines in Logcat signaling that ThumbnailDownloader is getting each one of your download requests.
Now that you have a HandlerThread up and running, the next step is to create a message with the
information passed in to queueThumbnail(), and then put that message on the ThumbnailDownloader’s
message queue.
Messages and Message Handlers
Before you create a message, you need to understand what a Message is and the relationship it has with
its Handler (often called its message handler).
Message anatomy
Let’s start by looking closely at messages. The messages that a Flash might put in an inbox (its own
inbox or that of another Flash) are not supportive notes, like, “You run very fast, Flash.” They are tasks
that need to be handled.
A message is an instance of Message and contains several fields. Three are relevant to your
implementation:
what a user-defined int that describes the message
obj a user-specified object to be sent with the message
target the Handler that will handle the message