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

(gtxtreme123) #1

Chapter 26  Loopers, Handlers, and HandlerThread


Assembling a Background Thread


Create a new class called ThumbnailDownloader that extends HandlerThread. Then give it a
constructor, a stub implementation of a method called queueThumbnail(), and an override of the
quit() method that signals when your thread has quit. (Toward the end of the chapter, you will need
this bit of information.)


Listing 26.4  Initial thread code (ThumbnailDownloader.java)


public class ThumbnailDownloader extends HandlerThread {
private static final String TAG = "ThumbnailDownloader";


private boolean mHasQuit = false;


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);
}
}


Notice that you gave the class a single generic argument, . Your ThumbnailDownloader’s user,
PhotoGalleryFragment in this case, will need to use some object to identify each download and to
determine which UI element to update with the image once it is downloaded. Rather than locking the
user into a specific type of object as the identifier, using a generic makes the implementation more
flexible.


The queueThumbnail() method expects an object of type T to use as the identifier for the download
and a String containing the URL to download. This is the method you will have PhotoAdapter call in
its onBindViewHolder(...) implementation.

Free download pdf