AlarmManager

编程入门 行业动态 更新时间:2024-10-17 13:37:34
本文介绍了AlarmManager - 如何在每一个小时的顶部重复一个报警?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我要为一个触发事件,每隔一小时(5:00,6:00,7:00,等等)。 我试着用一个线程的持久后台服务,但它不是因为正确的解决方案:

I want for an event to fire every hour (at 5:00, 6:00, 7:00, etc...). I tried with a persistent background service with a thread but it wasn't the right solution because of:

  • 在电池消耗
  • 在终止服务时,由于Android的内存管理

所以我想用AlarmManager。它的工作原理,如果我设置闹钟火秒钟后(使用设置的方法)。 但我怎么能重复的事件(使用setRepeating法),在每一个小时的顶部,直到报警被取消?

So I'm trying with AlarmManager. It works if I set an alarm to fire in X seconds (using "set" method). But how can I repeat an event (using "setRepeating" method) at the top of every hour, until the alarm is canceled?

谢谢!

推荐答案

在设置报警你有两次:一是触发时间,下一个触发间隔

When you set alarms you have two times: First trigger time, and the next trigger interval.

您接下来要计算剩余毫秒到小时的顶下,然后设置一个小时的重复间隔。

You then have to calculate the remaining miliseconds to the next top of the hour, then set one hour for the repeating interval.

// We want the alarm to go off 30 seconds from now. long firstTime = SystemClock.elapsedRealtime(); firstTime += remainingMilisecondsToTopHour; long a=c.getTimeInMillis(); // Schedule the alarm! AlarmManager am = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME, c.getTimeInMillis(), 1*60*60*1000, sender);

更多推荐

AlarmManager

本文发布于:2023-11-27 07:44:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637158.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:AlarmManager

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!