2

I use AsyncTasks in several places to do lengthy database queries and then fill in the resulting data Views in PostExecute. But by the time it gets there, the user could have switched screens (fragments) in my app or even "exited" the app back to the launcher.

Right now I use a somewhat kludgey method so that the AsyncTask can check to see if the Activity's still alive before making the updates. But is this really necessary? It seems like as long as the task is active that the various View objects still exist, so updating them, while useless, will not hurt anything.

Anyone have some ideas on coordinating the action of AsyncTasks in this regard?

gordonwd
  • 4,537
  • 9
  • 37
  • 53

2 Answers2

2

Keeping references to an activity that has ended can cause serious memory problems because it prevents everything associated with the activity from being gc'ed. There's an interesting thread on the Android Developer's group on this issue; the most useful post, I think, is here.

Also, see this thread for more on the flaws in AsyncTask and what to do about them.

EDIT: There's also this useful blog post by Santiago Lezica that's specific to using AsyncTask with fragments that have called setRetainInstance(true);.

Community
  • 1
  • 1
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • These pretty much summarize what I've already run into and have concluded about the gotchas of using AsyncTasks. Thanks for the tip! – gordonwd Feb 28 '12 at 15:55
0

Since your background tasks are pretty much confined to database queries, I might suggest using a CursorLoader instead of raw AsyncTask to query your data. If you are not targeting 3.0, you can still make use of them through the compatibility library. They are designed for just this purpose; allowing the system to manage the background task and the Cursor.

The Loader protocol communicates through a LoaderManager, which is bound to an Activity and handles whether or not to fire the callbacks, so you do not need to worry about unregistering, and if the user leaves before the latest refresh is complete it's no matter.

To read more information about implementing a Loader, read the associated developer guide: http://developer.android.com/guide/topics/fundamentals/loaders.html

HTH

devunwired
  • 62,780
  • 12
  • 127
  • 139
  • The Loaders are an interesting idea and I was unaware of them since I initially wrote this app when V2.2 was current. But I'm actually doing a lot more than just the queries in the background and am not sure if I could implement this approach. But I'll look into it. – gordonwd Feb 28 '12 at 15:54
  • It's pretty extensible, you could always make your own built on `CursorLoader` – devunwired Feb 28 '12 at 19:43