如何正确地将不断变化的数据从 AsyncTask 链接到 Activity 中的 TextView
假设我有一个 Activity
,它显示一个包含 TextView
的 View
。 我的 Activity
还有一个 AsyncTask
(连续运行),它每秒左右从 Web 服务器检索数据(变化的值)。 我想要的是通过在 TextView
中显示来自 Web 服务器的数据来监视数据。
到目前为止,我总是要求我的AsyncTask
在onProgressUpdate
中执行setText
,所以我的TextView
的显示是每次获得新数据时都会刷新...有更好的方法吗?
感谢您阅读我的内容。
PS:最后,我将至少有两个 Activity,它们都具有前面描述的各种 AsyncTask。
Let's say I have an Activity
which displays a View
containing a TextView
.
My Activity
also have an AsyncTask
(running continuously) which retrieve data (a changing value) from a web server every second or so.
What I want is to monitor the data from the web server by displaying it in the TextView
.
So far I always ask my AsyncTask
to do the setText
in the onProgressUpdate
, so my TextView
's display is refreshed every time I get new data... is there a better way ?
Thanks for reading me.
PS : In the end, I'll have at least two Activities, both having an AsyncTask of the previously described variety.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想分离数据并显示更多内容,您可以遵循侦听器模式:
让您的 Activity 实现一个新接口 - 类似于:
实现(在您的 Activity 中):
以及一个看起来像这样的 AsyncTask:
以及 Activity 保持对 UI 的控制,AsyncTask 会下载并在更新时发出通知。
If you want to separate the data and display a bit more, you could follow a listener pattern:
Make your Activity implement a new interface - something like:
and the implementation (in your Activity):
And a AsyncTask that looks something like this:
Your Activity keeps control of the UI, the AsyncTask downloads and notifies when something is updated.
好吧,如果获取的数据与之前获取的数据发生了变化,
TextView
的文本也应该发生变化(因此您必须调用setText
方法)。您可以存储最后的数据并根据最后一个onProgressUpdate
测试新数据,以便您仅在必要时更改TextView
的文本。例如,可以使用任何字符串匹配算法来完成测试。Well, if the fetched data changed from the preciously fetched, the text of the
TextView
should change as well (and so you have to call thesetText
method). You could store the last data and test the new data against the last oneonProgressUpdate
, so that you will only change theTextView
's text when necessary. The test can be done with any string matching algorithm, for example.