Epic Blog of Awesome


Proper use of AsyncTask

Using Android’s 3.0 Fragments API, available for versions 1.6+ in the Android Compatibility Package, we can create an extra layer around AsyncTask that fixes the problem while preserving the abstraction.

A Fragment can outlive its parent Activity through configuration changes by way of setRetainInstance(true). Even better, overriding the proper Fragment event callbacks, it’s possible to distinguish between a recreation and a real destruction, as well as knowing for sure when an Activity is ready to receive events.

We’ll see how to create a Fragment to manage our AsyncTask instances, and ensure a live Activity instance at the time onPostExecute() is called. The mechanism is completely independent from the specifics of the background work, so it’s simple to create a full abstraction that gives a safe execution environment for callbacks and preserves the ease of use of AsyncTask.

via Proper use of AsyncTask « blogActivity;.