Chapter 26 Loopers, Handlers, and HandlerThread
Next, add code to queueThumbnail(...) to update mRequestMap and to post a new message to the
background thread’s message queue.
Listing 26.8 Obtaining and sending a message (ThumbnailDownloader.java)
public class ThumbnailDownloader
private static final String TAG = "ThumbnailDownloader";
private static final int MESSAGE_DOWNLOAD = 0;
private boolean mHasQuit = false;
private Handler mRequestHandler;
private ConcurrentMap<T,String> mRequestMap = new ConcurrentHashMap<>();
public ThumbnailDownloader() {
super(TAG);
}
@Override
public boolean quit() {
mHasQuit = true;
return super.quit();
}
public void queueThumbnail(T target, String url) {
Log.i(TAG, "Got a URL: " + url);
if (url == null) {
mRequestMap.remove(target);
} else {
mRequestMap.put(target, url);
mRequestHandler.obtainMessage(MESSAGE_DOWNLOAD, target)
.sendToTarget();
}
}
}
You obtain a message directly from mRequestHandler, which automatically sets the new Message
object’s target field to mRequestHandler. This means mRequestHandler will be in charge of
processing the message when it is pulled off the message queue. The message’s what field is set to
MESSAGE_DOWNLOAD. Its obj field is set to the T target value (a PhotoHolder in this case) that is
passed to queueThumbnail(...).
The new message represents a download request for the specified T target (a PhotoHolder from the
RecyclerView). Recall that PhotoGalleryFragment’s RecyclerView’s adapter implementation calls
queueThumbnail(...) from onBindViewHolder(...), passing along the PhotoHolder the image is being
downloaded for and the URL location of the image to download.
Notice that the message itself does not include the URL. Instead you update mRequestMap with
a mapping between the request identifier (PhotoHolder) and the URL for the request. Later you
will pull the URL from mRequestMap to ensure that you are always downloading the most recently
requested URL for a given PhotoHolder instance. (This is important because ViewHolder objects in
RecyclerViews are recycled and reused.)