Chapter 26 Loopers, Handlers, and HandlerThread
In ThumbnailDownloader.java, add the mResponseHandler variable seen above to hold a Handler
passed from the main thread. Then replace the constructor with one that accepts a Handler and sets the
variable. Also, add a listener interface that will be used to communicate the responses (downloaded
images) with the requester (the main thread).
Listing 26.10 Handling 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<>();
private Handler mResponseHandler;
private ThumbnailDownloadListener
public interface ThumbnailDownloadListener
void onThumbnailDownloaded(T target, Bitmap thumbnail);
}
public void setThumbnailDownloadListener(ThumbnailDownloadListener
mThumbnailDownloadListener = listener;
}
public ThumbnailDownloader(Handler responseHandler) {
super(TAG);
mResponseHandler = responseHandler;
}
...
}
The onThumbnailDownloaded(...) method defined in your new ThumbnailDownloadListener interface
will eventually be called when an image has been fully downloaded and is ready to be added to
the UI. Using this listener delegates the responsibility of what to do with the downloaded image
to a class other than ThumbnailDownloader (in this case, to PhotoGalleryFragment). Doing so
separates the downloading task from the UI updating task (putting the images into ImageViews), so that
ThumbnailDownloader could be used for downloading into other kinds of View objects as needed.