最佳实践:在方向改变的AsyncTask方向、AsyncTask

2023-09-11 12:32:49 作者:学卜会坚强

AsyncTask的是一个伟大的事情在另一个线程中运行复杂的任务。

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

但是,当有一个方向变化或当AsyncTask的仍在运行另一种结构变化,当前的活动被破坏并重新启动。而作为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.

所以我要寻找某种最佳实践,以避免失败这些错误和prevent 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与新的活动实例更新它 在刚刚取消当活动被销毁任务和重新启动该活动再次创建时。 任务绑定到应用程序类,而不是活动实例。 在书架项目(通过onRestoreInstanceState)中使用的一些方法

有些code的例子:

在一个屏幕旋转的Andr​​oid AsyncTasks,第一部分和第二部分

ShelvesActivity.java

你能不能帮我找到它解决了这个问题最好的,易于实施,以及最好的办法? C本身的$ C $也很重要,因为我不知道如何正确地解决这个问题。感谢您的帮助: - )

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. Thanks for helping :-)

推荐答案

不要不会使用安卓configChanges 来解决这个问题。这是非常不好的做法。

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

不要不会使用活动#onRetainNonConfigurationInstance()无论是。这是不太模块化的,并不适合于片段基于应用程序。

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

您可以read我的文章 描述了如何使用保留的片段 s到处理配置更改。它解决了保留的的AsyncTask 跨越旋转变化很好的问题。基本上,您需要在您的的AsyncTask 片段,呼叫 setRetainInstance(真)片段,并报告的AsyncTask 的进步/结果回到它的活动通过保留片段的。

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.