Android AsycTask 和方向更改
当配置发生更改时,您应该如何处理 AsyncTasks。我通过这些任务访问 ReSTful API,在需要取回数据然后将其显示给用户的情况下,我遇到了问题。如果发生配置更改(例如方向更改),则活动无法正确更新。我相信 AsyncTask 正在更新已被销毁的旧活动。我找到了一个解决方案,需要在 Application 类中创建一个布尔值,用于跟踪我关心的 AsyncTask 是否仍在运行,然后在旋转时取消侦听器,然后在新的 Activity 中重新创建它,然后当 AsyncTask完成后,侦听器会将数据显示给用户。这很有效,但需要大量额外的工作并需要大量的管理。有没有一种方法可以将异步任务绑定到活动的新实例。或者一种抽象我所做的事情的方法,这样就不需要对每项任务进行太多的管理。 谢谢
How should you handle AsyncTasks when configuration changes occur. I am accessing a ReSTful API through these tasks, and in the cases where I need to get data back and then display it to the user I am experiencing problems. If a configuration change occurs, like an orientation change then the Activity is not properly update. I believe that the AsyncTask is updating the old activity that has been destroyed. I have found a solution to this that requires creating a boolean in the Application class that keeps track of whether the AsyncTask I care about is still running, and then on rotations I cancel the listener then recreate it in the new Activity, then when the AsyncTask is done, the listener then displays the data to the user. This works well, but it requires lots of extras and requires a lot of management. Is there a way that the async task can be tied to the new instance of the activity. Or a way to abstract what I have done, so it does not require as much management for each task you have.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看asynctask-screen-rotation。这个实现对我来说效果很好。
Have a look at asynctask-screen-rotation. This implementation is working quite good for me.
我也为此苦苦挣扎,我发现的最佳解决方案是将
android:configChanges="orientation"
添加到AndroidManifest.xml
文件中的活动中。这将阻止您的 Activity 在方向改变时被破坏和重新创建。I struggled with that a lot too, the best solution I found was to add
android:configChanges="orientation"
to your activity in theAndroidManifest.xml
file. This will stop your activity from being destroyed and recreated when the orientation changes.