最佳实践:方向更改时的AsyncTask [英] Best practice: AsyncTask during orientation change

查看:70
本文介绍了最佳实践:方向更改时的AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

所以,我正在寻找某种最佳实践来避免这些错误,并防止AsyncTask失败。

So, I am looking for some kind of "best-practice" to avoid these errors and prevent AsyncTask from failing.

我目前看到的是:


  • 禁用方向更改(肯定不是您应该处理的方式。)

  • 让该任务可以通过 onRetainNonConfigurationInstance

  • 通过新的活动实例进行更新。只需在活动中取消该任务即可被破坏,并在重新创建活动时重新启动。

  • 将任务绑定到应用程序类而不是活动实例。

  • 货架项目中使用的一些方法(通过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 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)

一些代码示例:

在屏幕旋转期间的Android AsyncTasks,第I部分和第一部分第二部分

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.

推荐答案

Do NOT 使用 android:configChanges 来解决这个问题。这是非常糟糕的做法。

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

执行使用活动#onRetainNonConfigurationInstance() 。这不是模块化的,并不适合 Fragment 的应用程序。

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

您可以微软阅读我的文章 描述如何使用保留的片段秒。它解决了保持一个 AsyncTask 的旋转变化很好的问题。您基本上需要在 Fragment 内托管您的 AsyncTask ,调用 setRetainInstance(true)片段,并将 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.

这篇关于最佳实践:方向更改时的AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆