如何以正确的方式定期运行代码
我需要下载一些数据并每隔一段时间解析结果。 现在,我从我的活动中启动一项服务,每隔几秒启动一个 TimerTask 。现在我读了一些有关 AlarmManager 和处理程序的内容,并对解决此类问题的多种方法感到困惑。
这是做这种事情的正确方法吗?
AlarmManager 适合什么类型的任务,Service(带有 TimerTask)适合什么类型的任务?
I need to download some data and parse the results at some intervals.
Right now i start a service from my actitivy that starts a TimerTask every few seconds. Now i read some things about AlarmManager and handler and got confused with so many ways of solving this kind of problems.
Is this the right way to do this kind of things?
For what kind of tasks is AlarmManager and for what kind of tasks is Service (with TimerTask)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您希望您的应用程序在特定时间间隔执行某些操作(即使您的应用程序未使用时)时,请使用 AlarmManager。 AlarmManagers 广播该事件并启动附加到该事件的意图,这将是您的应用程序。
当您需要在当前使用应用程序的时间间隔内执行某些操作时,可以使用计时器和计时器任务。因此,当您的应用程序关闭时,您将取消所有计时器。并且只有在您下次打开应用程序时它才会重新启动。
AlarmManagers are used when you want your app to do something at specific intervals even when your app is not used. AlarmManagers broadcast the event and starts the intent thats attached to it which will be your app.
Timers and TimerTasks are used when you need to do some operation during intervals while your app is currently used. So when your app is closed you cancel all the timers. And it will only start again the next time you open the app.