最佳实践:方向更改期间的 AsyncTask [英] Best practice: AsyncTask during orientation change
问题描述
AsyncTask
是在另一个线程中运行复杂任务的好东西.
AsyncTask
is a great thing to run complex tasks in another thread.
但是当 AsyncTask
仍在运行时发生方向更改或其他配置更改时,当前的 Activity
将被销毁并重新启动.当 AsyncTask
的实例连接到该活动时,它会失败并导致强制关闭"消息窗口.
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.
所以,我正在寻找某种最佳实践"来避免这些错误并防止 AsyncTask 失败.
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:
- 禁用方向更改.(肯定不是你应该处理的方式.)
- 让任务存活并通过
onRetainNonConfigurationInstance
用新的活动实例更新它 Activity
销毁时取消任务,Activity
再次创建时重新启动.- 将任务绑定到应用程序类而不是活动实例.
- 货架"项目中使用的一些方法(通过 onRestoreInstanceState)
- 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)
一些代码示例:
Android AsyncTasks 在屏幕期间旋转,第一部分和第二部分
您能帮我找到最能解决问题且易于实施的最佳方法吗?代码本身也很重要,因为我不知道如何正确解决这个问题.
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.
推荐答案
不要不使用 android:configChanges
来解决这个问题.这是非常糟糕的做法.
Do NOT use android:configChanges
to address this issue. This is very bad practice.
不要不使用Activity#onRetainNonConfigurationInstance()
.这不是模块化的,不适合基于 Fragment
的应用程序.
Do NOT use Activity#onRetainNonConfigurationInstance()
either. This is less modular and not well-suited for Fragment
-based applications.
您可以阅读我的文章 描述如何使用保留的 Fragment
处理配置更改.它很好地解决了在旋转更改中保留 AsyncTask
的问题.您基本上需要在 Fragment
中托管您的 AsyncTask
,在 Fragment
上调用 setRetainInstance(true)
,然后报告AsyncTask
的进度/结果通过保留的 Fragment
回到它的 Activity
.
You can read my article describing how to handle configuration changes using retained Fragment
s. 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
.
这篇关于最佳实践:方向更改期间的 AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!