0

There is an AsyncTask that fetches something from the web and then calls Activity.showDialog in onPostExecute(...). What exactly happens if

  1. I start AsyncTask in Activity B
  2. Go back to Activity A
  3. AsyncTask finishes it's job (doInBackground() returns)

? Is onPostExecute() called?

fhucho
  • 34,062
  • 40
  • 136
  • 186

2 Answers2

3

Depending on how your AsyncTask is implemented you might "leak" Activity B until the AsyncTask finishes. Ideally, your AsyncTask should be cancelled when Activity B is destroyed.

Romain Guy
  • 97,993
  • 18
  • 219
  • 200
  • My AsyncTask is a static class, reference to the Activity is set by setActivity() method. I return the AsyncTask in onRetainNonConfigurationInstance() - and after orientation change I retrieve it with getLastNonConfigurationInstance() and call setActivity(). I see WindowManager.BadTokenException reports in Android Market, can it be caused by the way how I use AsyncTask? – fhucho Feb 11 '11 at 22:23
  • @fhucho: Possibly. You cannot safely reference the `Activity` from `doInBackground()`. If you avoid that and call `setActivity()` again from `onCreate()` of the new activity instance, in theory, you should be safe. Leastways, that was the net result of an exchange I had with Ms. Hackborn on the `android-developers` group some time ago. – CommonsWare Feb 11 '11 at 23:07
  • @CommonsWare I am using the pattern you described here: http://stackoverflow.com/questions/3821423/background-task-progress-dialog-orientation-change-is-there-any-100-working/3821998#3821998 (please see my comment). However I noticed I don't detach the Activity, which could be the problem. – fhucho Feb 13 '11 at 16:33
0

I found out that the fact that my Activity finishes has no effect on the AsyncTask. I have showDialog() call in my onPostExecute(). This is causing force close when the user presses BACK, the Activity finishes and onPostExecute() is called.

fhucho
  • 34,062
  • 40
  • 136
  • 186
  • You should always check before creating a dialog, if you still have context/activity you can work on. – WarrenFaith Feb 13 '11 at 19:35
  • Yes... I am using this pattern - http://stackoverflow.com/questions/3821423/background-task-progress-dialog-orientation-change-is-there-any-100-working/3821998#3821998. I will have to do a small modification to fix this bug. Right now I am detaching my Activity from the AsyncTask in onRetainNonConfigurationInstance(). I will move the detach to onDestroy(), which should solve my problem. – fhucho Feb 13 '11 at 19:41