Android 方向更改后从 AsycTask 更新 UI
我正在使用 AsyncTask 从服务器检索一些显示在屏幕上的数据。问题是,如果我在检索数据时更改设备的方向(显示进度条),我的 UI 不会更新。
我已执行以下操作来处理这种情况:
a)重写 onRetainNonConfigurationInstance,它返回我的 AsychTask 的实例,在 onCreate 方法上检索它。 b) 将我的小部件声明为易失性的 c) 通过从 AsycTask 的 postExecute 调用 setContentView 重绘整个 U d) 在小部件上调用 invalidate 方法
我在屏幕上没有收到任何错误,我的应用程序没有崩溃,但 UI 也没有更新。 我已经在调试模式下执行了代码,更新 UI 的代码实际上被执行了,但它什么也没做。
在日志中,我看到一个错误,指出我的活动泄漏了一个窗口。
任何建议我做错了什么或没有做我应该做的事情。
I am using AsyncTask to retrieve some data from Server which is displayed on the screen. The issue is if I change the orientation of the device while data is being retreieved (a progress bar being displayed), my UI does not get updated.
I have done following to handle this situation:
a) override onRetainNonConfigurationInstance which returns the instance of my AsychTask, retrieve this on onCreate method.
b) Declared my widgets as volatile
c) Redraw the entire U by calling setContentView from postExecute of the AsycTask
d) invoked invalidate method on the widgets
I do not get any errors on screen, my application does not crashed but the UI is not updated either.
I have executed the code on debug mode, the code which updates the UI is actually executed, but it does nothing.
In logs I see one error saying my Activity has leaked a window.
Any suggestions what I am doing wrong or not doing something which I should be doing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题几乎可以肯定是您的 AsyncTask 保留了对旧 Activity 的引用。 (也许这是一个内部类?)这是一个出乎意料的困难问题。 此帖子对困难进行了精彩的讨论,并提供了一些解决方案 在 Google 群组中。向下滚动查看 Lance Nanek 的答案,了解一些解决此问题的代码。
该问题并非 AsyncTask 特有的;它可能发生在任何需要与 UI 交互的后台线程中,并且还需要在配置更改带来的销毁/启动生命周期事件中幸存下来。
The problem is almost certainly that your AsyncTask is keeping a reference to the old Activity. (Perhaps it's an inner class?) This is a surprisingly difficult problem. There's an excellent discussion of the difficulties, as well as some solutions, on this thread at Google groups. Scroll down for the answers by Lance Nanek for some code that gets around this.
The problem is not specific to AsyncTask; it can happen with any background thread that needs to interact with the UI and also needs to survive the destroy/start lifecycle events that come with a configuration change.