Android Programming: The Big Nerd Ranch Guide, 2nd Edition
by Bill Phillips, Chris Stewart, Brian Hardy, Kristin Marsicano
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. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access