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的例子:
在一个屏幕旋转的Android 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 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
.
上一篇:是否有可能宣布在摇篮一个变量在Java中使用吗?有可能、摇篮、变量、Java
下一篇:如何注册某些URL命名空间(的myapp://app.start/)通过调用浏览器的URL在Android操作系统访问你的程序?你的、浏览器、操作系统、程序