Android,是否可以使用系统计时器作为广播接收器?
在我的应用程序中,我需要根据我的用户偏好每 5 秒、10 秒或 1 分钟刷新一次数据。
我可以创建线程并使用计时器类,但我想知道还有其他方法吗?例如,系统计时器发送标志(广播某些内容),我在应用程序中获取它(以便刷新我的数据)?
谢谢
In my application I need to refresh my data in each 5s or 10s or 1 minute, according to my user preference.
I can create thread and use timer class but i want to know is there any other way? for example timer of system sends flag (broadcast something) and i get it in application (in order to refresh my data)?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你想每隔几秒刷新一次数据,你可以设置一个 Hanlder 来执行此操作。但是,这需要您的活动持续运行。
如果您想在特定时间做某事,例如闹钟。您可以使用 AlarmManager。这将启动您的活动或其他组件,即使它现在没有运行。
如果你只是想监控系统时间的变化。好吧,有一个 Intent ACTION_TIME_TICK 。您可以注册一个 BroadcastReceiver 来监听它,并在 systemt 广播它时实现您自己的代码。然而,“TICK”间隔仅为“一分钟”且无法更改。
If you want to refresh the data every serval seconds, you can setup a Hanlder to do this. However, this requires your activity keeps running.
If you want to do something at a specific time, like an Alarm. You can use the AlarmManager. This would lauch your activity or other components even it is not running now.
If you just want to moniter the change in the system time. Well, there is a Intent ACTION_TIME_TICK . You can register a BroadcastReceiver to listent to it and implement your own code when the systemt brocasts it. However, the "TICK" interval is "One Minute" only and can not be changed.
AlarmManager 就是您正在寻找的。它可用于设置通过 PendingIntent 传递的周期性事件(可以变成Intent广播)。
我会谨慎地定期检查新数据,除非设备始终连接到电源,特别是当您通过网络进行检查时。由于网络的轮询间隔很短,电池在几个小时内就会耗尽。
AlarmManager is what you are looking for. It can be used to set up periodic events that are delivered via a PendingIntent (which can be turned into an Intent broadcast).
I would be wary checking for new data on such a regular interval unless the device is always connected to a power source, especially if you are making the check over a network. With that small a poll interval going to the nework the battery will be flat in hours.