避免在 Android 中方向改变时使用 asynctask 重新加载 Activity
在android中,当用户改变方向时,如何避免在活动中使用asynctask类重新加载活动?有人可以举个例子吗?
How do I avoid reloading the activity with asynctask class in activity when the user changes orientation, in android? Can anybody give an example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
作为最后的手段,请关闭配置更改。发生这种情况时,您的应用必须正常工作。如果您关闭方向配置更改,因为它会中断,您的应用程序仍会以其他方式(有时甚至是更微妙的方式)中断。允许由于方向配置更改而重新启动 Activity 是一种非常好的方法,可以轻松测试应用程序的这些重要代码路径,否则这些路径很少会被执行,但仍然会导致用户失败。
要跨 Activity 实例传输活动对象,请使用新的片段静态库,它允许您创建跨实例保留的片段。
Please turn off config changes as a last resort. Your app must work correctly when this happens. If you turn off the orientation config change because it breaks, your app will still break in other and some times more subtle way. Allowing the activity to be restarted due to an orientation config change is a very good way to easily test these important code paths of your app that are otherwise much less often exercised but still will result in failures in your users' hands.
To transfer active objects across Activity instances, use the new fragment static library which allows you to make a fragment that is retained for you across instances.
奇拉格已经正确地指出了解决方案。
我只是想补充一点,Activity的重启与其中的
AsyncTask
无关。默认情况下,当有任何配置更改时,活动将重新启动,除非活动显式处理配置更改。这是通过在清单文件中创建一个条目来完成的。浏览此链接开发人员指南:android:configChanges
注意:在设备上而不是模拟器上检查代码。因为我之前也遇到过类似的问题。相同的代码在模拟器上不起作用,但在设备上完美运行。因此,在清单中添加
android:configChanges
条目,并在 Android 设备而不是模拟器上检查应用程序。我第二个@hackbod。 仅在必要时才这样做!
Chirag have already correctly pointed out the solution.
I just want to add that, restart of Activity has nothing to do with the
AsyncTask
in it. By default, when there are any config changes,the activity is restarted UNLESS the config change is explicitly handled by the Activity. This is done by making an entry in manifest file.Go through this link developer guide : android:configChanges
NOTE: Check the code on a device not on emulator. Because I had faced similar problem earlier. The same code didn't worked on emulator but it worked on device perfectly. So add the entry for
android:configChanges
in manifest and check the application on a android device instead of emulator.And I second @hackbod. Do it only if necessary!