Android,是否可以使用系统计时器作为广播接收器?

发布于 2024-12-11 12:16:10 字数 140 浏览 0 评论 0原文

在我的应用程序中,我需要根据我的用户偏好每 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

自由如风 2024-12-18 12:16:10

如果你想每隔几秒刷新一次数据,你可以设置一个 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.

无语# 2024-12-18 12:16:10

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文