Android – Best practice: AsyncTask during orientation change

androidexceptionmultithreading

AsyncTask is a great thing to run complex tasks in another thread.

But when there is an orientation change or another configuration change while the AsyncTask is still running, the current Activity is destroyed and restarted. And as the instance of AsyncTask is connected to that activity, it fails and causes a "force close" message window.

So, I am looking for some kind of "best-practice" to avoid these errors and prevent AsyncTask from failing.

What I've seen so far is:

  • Disable orientation changes.(For sure not the way you should handle this.)
  • Letting the task survive and updating it with the new activity instance via onRetainNonConfigurationInstance
  • Just canceling the task when the Activity is destroyed and restarting it when the Activity is created again.
  • Binding the task to the application class instead of the activity instance.
  • Some method used in the "shelves" project (via onRestoreInstanceState)

Some code examples:

Android AsyncTasks during a screen rotation, Part I and Part II

ShelvesActivity.java

Can you help me to find the best approach which solves the problem best and is easy to implement as well? The code itself is also important as I don't know how to solve this correctly.

Best Answer

Do NOT use android:configChanges to address this issue. This is very bad practice.

Do NOT use Activity#onRetainNonConfigurationInstance() either. This is less modular and not well-suited for Fragment-based applications.

You can read my article describing how to handle configuration changes using retained Fragments. It solves the problem of retaining an AsyncTask across a rotation change nicely. You basically need to host your AsyncTask inside a Fragment, call setRetainInstance(true) on the Fragment, and report the AsyncTask's progress/results back to it's Activity through the retained Fragment.