Play with this demo

In this Activity, you can :

Read below to learn more.

Advanced AsyncTask usage 2/2.

This Activity uses an AsyncTask declared as a static inner class.
The Activity holds a WeakReference on the AsyncTask and the AsyncTask uses a WeakReference on the Activity (2-way weak references).

Memory leak issue

This technique definitely solves the problem : AsyncTask doesn't hold any hard reference to the activity and the other way around. This way, the AsyncTask itself never prevents the Activity from being garbage collected. There is no memory leak at all using this technique.

Nevertheless, the technique proposed here :

Conclusion on AsyncTasks

This demo Activty illustrates how difficult it is to get a robust implementation of AsyncTasks. It is possible to achieve a working solution with no memory leak, but not in the same way for all versions of Android (with respect to backward compatibility support library). The conclusion of this serie is that : Yes, Loaders are the way to go, just forget AsyncTasks for long running asynchronous jobs.


Loaders offer a more modern implementation of Asynchronous job executions and we will illustrate how to use them in the next serie of this tutorial application.