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 theActivity
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
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 forFragment
-based applications.You can read my article describing how to handle configuration changes using retained
Fragment
s. It solves the problem of retaining anAsyncTask
across a rotation change nicely. You basically need to host yourAsyncTask
inside aFragment
, callsetRetainInstance(true)
on theFragment
, and report theAsyncTask
's progress/results back to it'sActivity
through the retainedFragment
.