Using handlers
Figure 26.6 shows the object relationships involved.
Figure 26.6 Creating a Message and sending it
In this case, your implementation of handleMessage(...) will use FlickrFetchr to download bytes
from the URL and then turn these bytes into a bitmap.
First, add the constant and member variables as shown in Listing 26.7.
Listing 26.7 Adding constant and member variables
(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<>();
...
}
MESSAGE_DOWNLOAD will be used to identify messages as download requests. (ThumbnailDownloader
will set this as the what on any new download messages it creates.)
The newly added mRequestHandler will store a reference to the Handler responsible for queueing
download requests as messages onto the ThumbnailDownloader background thread. This handler will
also be in charge of processing download request messages when they are pulled off the queue.
The mRequestMap variable is a ConcurrentHashMap, a thread-safe version of HashMap. Here, using a
download request’s identifying object of type T as a key, you can store and retrieve the URL associated
with a particular request. (In this case, the identifying object is a PhotoHolder, so the request response
can be easily routed back to the UI element where the downloaded image should be placed.)