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.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…