Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android context leaks in AsyncTask

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?

like image 591
hpique Avatar asked Nov 18 '10 23:11

hpique


1 Answers

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();
like image 110
Tom Neyland Avatar answered Sep 19 '22 04:09

Tom Neyland