Since AsyncTask was introduced in Cupcake (API 3, Android 1.5) in 2009, it has been consistently promoted by the Android team as simple:
- "Painless threading"
- "an easy way to execute some work in a background thread and publish the results back on the UI thread".
- "one of the simplest ways to fire off a new task from the UI thread"
The code samples which they provide reinforce this message of simplicity, especially to those of us who have had to work with threads in more painful ways. AsyncTask is very attractive.
Yet in the many years since, crashes, memory leaks, and other problems have plagued most developers who have chosen to use AsyncTask in their production applications. This is often due to Activity destruction and recreation on runtime configuration change (especially orientation/rotation) while the AsyncTask is running doInBackground(Params...) ; when onPostExecute(Result) is called, the Activity has already been destroyed, leaving UI references in an unusable state (or even null).
And the lack of obvious, clear, and concise guidance and code samples from the Android team on this issue has only made things worse, leading to confusion as well as various workarounds and hacks, some decent, some terrible:
- Is AsyncTask really conceptually flawed or am I just missing something?
- Best practice: AsyncTask during orientation change
- Lock orientation until Asynctask finish
Obviously, since AsyncTask can be used in many situations, there is no One Way to accommodate this issue. My question, however, is about options.
What are the canonical (endorsed by the Android team) best practices, with concise code samples, for integrating AsyncTask with the Activity/Fragment lifecycle and automatic restarts on runtime configuration change?