使用什么:服务或线程
我正在开发一个 Android 应用程序,它每 n 分钟从网络服务获取/上传数据。此上传/下载仅在应用程序运行时完成。但这种情况将来可能会改变。
下载新数据时我不更新用户界面。仅当用户位于当前屏幕上时(应用程序有多个活动),UI 才会更新
我的问题是解决此问题的最佳方法是什么。 我认为服务不是正确的方法,因为它听起来像是一种矫枉过正(在目前的情况下)。 AlarmManager 可能是一个选项。 在服务内运行线程是一个选项..类似于 this< /a> .
任何指示/建议都会很棒。 谢谢
I am developing an android app which fetches/uploads data from/to the web service every n minutes. This upload/download is only done when the app is running. But this might change in future.
I dont update the UI when the new data is downloaded. The UI is only updated if the user is on the current screen(app have multiple activities)
My question is what is the best approach to this problem.
I dont think service is the right approach as it sounds like an overkill(in the present scenario). AlarmManager could be an option.
Running threads inside a service be an option ..something like this .
Any pointers/suggestions would be great.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我在我的活动中使用 AsyncTask 来询问 .net Web 服务一些信息它有效且易于使用。
I am using AsyncTask in my activity to ask .net web service some information and it works and easy to use.
好吧,在这种情况下,由于应用程序在此期间已经在运行,所以两者都可以很好地工作,但是可以从应用程序内的任何位置调用服务,因此这就是我通过线程使用服务的地方。
如果您想创建仅在
Main.java
中使用的线程,那么线程可以正常工作,这些是我能看到的唯一真正产生任何差异的东西,它们是非常接近,在这种情况下都没有给出明显的“正确”答案,但我会选择服务Well, in this case, since the app would already be running during the time, either would work great, but a service can be called from anywhere within the application so this is where I would use the service over the thread.
If you want to create the thread to only be used in lets say
Main.java
, then thread would work fine, these are the only things that I can see really making ANY difference at all, they're really pretty close, and in this case neither gives a distinct "correct" answer, but I would choose Service我认为您提到的所有方法都可以正常工作。就我个人而言,我会这样做:
使用 AlarmManager 唤醒下载服务。当Activity显示时启动它,当Activity隐藏时停止它。
下载服务应该是短暂的:启动它进行上传/下载,然后关闭它。
如果下载服务确实获取了一些新数据,它会发送一个 Activity 监听的广播。
I think all approaches you noted would work ok. Personally I'd go with this:
Use AlarmManager to wake download service. Start it when Activity is shown, stop it when activity hidden.
Download service should be short lived: start it to do the upload/download and then shut it down.
If download service does get some new data, it sends a Broadcast which Activity listens to.
只需在上传/下载完成后广播一条消息,然后让接收者启动服务,然后让该服务自行停止。你就完成了。
如果您不打算轮询服务器以获取新信息或任何内容,则应该执行此操作。这种方法主要是一次性更新、解释、完成。并等待下一次更新。对于大多数情况来说,这主要是流式传输..但这取决于您获得的内容。
Just broadcast a message after your upload/download is done, and then have a receiver start the service and then have that service stop itself. And you are done.
This should be done if you dont plan on polling the server for new information or anything. Primarily this kind of approach would be for onetime update, interpret, finish. And wait until the next update. Which primarily for most cases is streaming.. but depends on what you are getting.