I have tested the statement that AsyncTasks are not destroyed along with their launching activity. And it is true.
I made the AsyncTask just publish a Log.i() message every 3 seconds for 1 minute. And I put Log.i() messsage in the onDestroy() method of the activity.
I see the activity is destroyed, but the AsyncTask keeps running until it finishes all 20 Log.i() messages.
And I am confused.
-
What if the AsyncTask had
publishProgress()into the destroyed UI?
I guess some sort of exception would occurr, right? -
What if the AsyncTask stores data in a global variable of
class Application?
No idea here, NullPointer exception? -
What if the app is restarted?
It will probably launch a new AsyncTask. Can it reconnect with the still running AsyncTask? -
Is the AsyncTask immortal after the mother app is destroyed?
Maybe yes, how do all LogCat apps keep logging messages while the UI application is not visible anymore, maybe destroyed? And when you reopen them they show you the messsages that were generated while it was ‘dead’.
All this seems like a discussion, but the question is in the title. I have this orphan AsyncTask, which I would like very much to reconnect to when the app is relaunched, but I don’t know how to do it.
I forgot to tell why this is very important. The app gets destroyed when an orientation change occurs. And I don’t want to loose the data produced by the AsyncTask, I don’t want to stop it and restart it. I just want it to keep going and reconnect after the orientation changes are done.
I hope I’ve got this right as it’s from some old code I no longer use (I now use an
IntentServiceto do what this used to do).This is what I originally had when I downloaded files in my main
Activity…The key is to use
onRetainNonConfigurationInstance()to ‘save’ theAsyncTask.I then have a method called
doDownload()which is called fromonResume()if aBooleanindicatingdownloadCompleteis true. TheBooleanis set in theonPostExecute(...)method ofFileDownloader.