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

(gtxtreme123) #1
Assembling a Background Thread

Open PhotoGalleryFragment.java. Give PhotoGalleryFragment a ThumbnailDownloader member
variable. In onCreate(...), create the thread and start it. Override onDestroy() to quit the thread.


Listing 26.5  Creating ThumbnailDownloader (PhotoGalleryFragment.java)


public class PhotoGalleryFragment extends Fragment {


private static final String TAG = "PhotoGalleryFragment";


private RecyclerView mPhotoRecyclerView;
private List mItems = new ArrayList<>();
private ThumbnailDownloader mThumbnailDownloader;
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
new FetchItemsTask().execute();


mThumbnailDownloader = new ThumbnailDownloader<>();
mThumbnailDownloader.start();
mThumbnailDownloader.getLooper();
Log.i(TAG, "Background thread started");
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
}


@Override
public void onDestroy() {
super.onDestroy();
mThumbnailDownloader.quit();
Log.i(TAG, "Background thread destroyed");
}
...
}


You can specify any type for ThumbnailDownloader’s generic argument. However, recall that this
argument specifies the type of the object that will be used as the identifier for your download. In this
case, the PhotoHolder makes for a convenient identifier as it is also the target where the downloaded
images will eventually go.


A couple of safety notes. One: Notice that you call getLooper() after calling start() on your
ThumbnailDownloader (you will learn more about the Looper in a moment). This is a way to ensure
that the thread’s guts are ready before proceeding, to obviate a potential (though rarely occurring) race
condition. Until you call getLooper(), there is no guarantee that onLooperPrepared() has been called,
so there is a possibility that calls to queueThumbnail(...) will fail due to a null Handler.


Safety note number two: You call quit() to terminate the thread inside onDestroy(). This is critical. If
you do not quit your HandlerThreads, they will never die. Like zombies. Or rock and roll.

Free download pdf