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

(gtxtreme123) #1

Cleaning Up AsyncTasks


Cleaning Up AsyncTasks


In this chapter, your AsyncTask and other code was carefully structured so that you would not
have to keep track of the AsyncTask instance. For example, you retained the fragment (called
setRetainInstance(true)) so that rotation does not repeatedly fire off new AsyncTasks to fetch the
JSON data. However, in other situations you will need to keep a handle on your AsyncTasks, even
canceling and rerunning them at times.


For these more complicated uses, you will want to assign your AsyncTask to an instance variable. Once
you have a handle on it, you can call AsyncTask.cancel(boolean). This method allows you to cancel
an ongoing AsyncTask.


AsyncTask.cancel(boolean) can work in a more rude or less rude fashion. If you call
cancel(false), it will be polite and simply set isCancelled() to true. The AsyncTask can then
check isCancelled() inside of doInBackground(...) and elect to finish prematurely.


If you call cancel(true), however, it will be impolite and interrupt the thread doInBackground(...)
is on, if it is currently running. AsyncTask.cancel(true) is a more severe way of stopping the
AsyncTask. If you can avoid it, you should.


When and where should you cancel your AsyncTask? It depends. First, ask yourself whether the work
the AsyncTask is doing should stop if the fragment or activity is destroyed or goes out of view. If so,
you should cancel the AsyncTask instance in either onStop(...) (to cancel the task when the view is no
longer visible) or onDestroy(...) (to cancel the task when the fragment/activity instance is destroyed).


What if you want the work the AsyncTask is doing to survive the life of the fragment/activity and
its view? You could just let the AsyncTask run to completion, without canceling. However, this has
potential for memory leaks (e.g., the Activity instance being kept alive past when it should have been
destroyed) or problems related to updating or accessing the UI when it is in an invalid state. If you have
important work that must be completed regardless of what the user is doing, it is better to consider
alternative options, such as launching a Service (which you will learn more about in Chapter 28).

Free download pdf