13

If I interpret this article correctly, passing the activity context to AsyncTasks is a potential leak, as the activity might be destroyed while the task is still running.

How do you deal with this in AsyncTasks that are not inner clases and need access to resources or to update the UI?

Additionally, how can you avoid leaking the context if you need references to progress dialogs to dismiss them?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
hpique
  • 119,096
  • 131
  • 338
  • 476
  • Look at [this](http://stackoverflow.com/questions/3821423/background-task-progress-dialog-orientation-change-is-there-any-100-working/3821998#3821998). It is about orientation changes but this deals with securely keeping a reference to an activity/context. – Kevin Gaudin Nov 18 '10 at 23:29

1 Answers1

14

If I understand your question correctly: Java's WeakReference or SoftReference class is a good fit for this type of situation. It will allow you to pass the context to the AsyncTask without preventing the GC from freeing the context if necessary.

The GC is more eager when collecting WeakReferences than it is when collecting SoftReferences.

instead of:

FooTask myFooTask = new FooTask(myContext);

your code would look like:

WeakReference<MyContextClass> myWeakContext = new WeakReference<MyContextClass>(myContext);
FooTask myFooTask = new FooTask(myWeakContext);

and in the AsyncTask instead of:

myContext.someMethod();

your code would look like:

myWeakContext.get().someMethod();
Tom Neyland
  • 6,860
  • 2
  • 36
  • 52
  • 5
    just make sure myWeakContext.get() does not return null, otherwise you screwed. – Radu Comaneci Jun 26 '13 at 18:36
  • This works if you don't strictly need to do the UI updates after the task finishes. If the results of the async task are needed after the activity is re-created, you'll need to use a different approach. Headless fragments set to retain state can manage your tasks. – r1k0 Jan 19 '15 at 10:00