Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

android - Best practice: AsyncTask during orientation change

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...