为后台任务选择哪一个 - 具有重复任务的计时器还是具有循环的服务?
当我在应用程序中收到广播时,我有一个重复的任务(任务 A)要做。我需要知道这些选项中哪一个更好地完成重复任务?
- 独立类中的计时器以及任务 A 是否重复计时器到期?
- 一个android后台服务正在执行任务A。
选择上述方法有何优缺点?
I have a repeated task(Task A) to do when I receive a broadcast in my application. I need to know which one is better between these options to do the repeated task?
- A Timer in a standalone class and does the Task A repeatedly on timer expiry?
- An android background service doing the Task A.
what are the pros and cons in choosing the above methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎假设所有可能的“任务 A”实现都是平等的。您似乎还假设所有周期(一毫秒到一世纪)都是平等的。这些都不是真的。
不可能抽象地回答你的问题,要解释所有的可能性需要几十页纸。
如果您需要定期使用设备位置更新 Web 服务器,并且轮询周期合理(例如,每个30 分钟),最好的选择是使用
AlarmManager
和Service
。我编写了一个LocationPoller
,它是专为这种情况设计的,另一个开发人员改进了。请记住,可能无法在任何给定时刻确定设备的位置,因此您需要有一个“超时”机制,以防找不到位置,因为找到位置会占用 CPU(和 GPS 无线电、如果相关)已通电。LocationPoller
就有这样的“超时”。You seem to assume that all possible "Task A" implementations are created equal. You also seem to assume that all periods (one millisecond to one century) are created equal. Neither of these are true.
It is impossible to answer your question in the abstract, and it would take a few dozen pages to explain all the possibilities.
If you need to periodically update a Web server with the device location, and the polling period is sensible (e.g., every 30 minutes), your best option is to use
AlarmManager
and aService
. I wrote aLocationPoller
which was designed for this scenario, which another developer has improved upon. Just bear in mind that it may not be possible to determine the device's location at any given moment, so you need to have a "timeout" mechanism in case you cannot find the location, since finding the location keeps the CPU (and GPS radio, where relevant) powered on.LocationPoller
has such a "timeout".