Here’s the scenario:
- Activity “A” creates and executes AsyncTask “T”
- As “T” is running in the background, the user moves away from “A”
- Examples of how the user could move away from “A”:
- Pressing “go” and starting an Intent launching Activity “B” (most common in my app)
- Pressing the “back” button (also fairly common in my app)
- Rotating the screen, without android:configChanges=”orientation|keyboardHidden”
- etc.
- Examples of how the user could move away from “A”:
- “T” has done its work and returns, trying to call function “F” on “A” to update “A”‘s UI, but “A” is… “gone”?!
How can I make sure the above does not “bomb”?
A very common hurdle in Android development. When I first stumbled on this issue, I found this Q with a lot of great discussion that illuminated things for me:
Is AsyncTask really conceptually flawed or am I just missing something?
It is imperative on you, the author of the AsyncTask, to ensure that it’s orphaned completion is ‘safe’ or else to cancel/abort. The conventional wisdom is to cancel (or at least logically dissociate via some mechanism of your own rolling, as @iagreen proposes) the Task instance from within your Activity’s onPause or onDestroy.
Ideal way to cancel an executing AsyncTask
There is frequent guidance around the web from Android team members that AsyncTask is intended to be for short operations whose lifecycle closely matches the ‘intended’ lifecycle of its parent activity, so if you find yourself doing longrunning operations and having to resume partial progress, etc you might want to look at explicit thread management or coding up a Service, etc:
http://developer.android.com/reference/android/app/Service.html