Android实时查询Web服务
我编写了一个应用程序来查询我编写的 Web 服务(返回 JSON 数据)。我的应用程序当前使用 AsyncTask 处理 Web 服务调用,并使用接收到的数据更新 TableLayout。我希望我的应用程序定期(大约每秒)调用此 Web 服务并在数据库中显示数据,因为它正在不断更新。我怎样才能在没有 UI 线程阻塞的情况下做到这一点?
目前的工作方式是用户按下“开始”按钮,AsyncTask 在请求处理时显示“正在加载”对话框。我希望他们按一次“执行”按钮并在布局中刷新数据。我不确定构建这个的最佳方法是什么。
I have written an application that queries a web service I wrote (which returns JSON data). My app currently processes the web service call using an AsyncTask and updates a TableLayout with the data it receives. I want my app to regularly (every second or so) call this web service and display the data in the DB, as it is continuously being updated. How can I go about doing this without having the UI thread block?
Currently the way things work is the user presses a "go" button, and the AsyncTask displays a "loading" dialog while the request processes. I would like for them to press the go button once and have the data refresh in the layout. I'm not sure what the best way to architect this is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不建议您每秒创建一个新的 AsyncTask,因为这将导致大量的对象创建和相应的内存收集。
您可以做的是创建一个
AsyncTask
,在每个请求从 Web 服务返回后更新一些内部数据结构,然后调用publishProgress()
,等待适当的时间,然后向 Web 服务发出新请求。在onPublishProgress()
中,代码应该从正在使用的任何内部结构的请求中获取新信息(不要忘记在此处使用锁来同步访问)并刷新 UI。您还需要
AsyncTask
有一个Activity
可以调用的方法或变量来告诉它跳出循环。I wouldn't recommend that you create a new
AsyncTask
every second since this is going to result in a lot of object creation and corresponding memory collection.What you can do instead is create an
AsyncTask
that after each request returns from the web service updates some internal data structures and then callspublishProgress()
, waits the appropriate amount of time, then makes a new request to the web service. InonPublishProgress()
the code should then get the new information from the request from whatever internal structures are being used (don't forget to use a lock here to synchronize access) and refresh the UI.You'll also want the
AsyncTask
to have a method or variable that theActivity
can call to tell it to break out of the loop.您可以使用 Handler ,它可以每秒发起一个新的 AsyncTask 请求。
You can use a Handler which can initiate a new AsyncTask request after every second.