简体   繁体   English

AlarmManager - 如何在每小时的顶部重复闹钟?

[英]AlarmManager - How to repeat an alarm at the top of every hour?

I want for an event to fire every hour (at 5:00, 6:00, 7:00, etc...). 我想要每小时开一次活动(5:00,6:00,7:00等)。 I tried with a persistent background service with a thread but it wasn't the right solution because of: 我尝试使用线程的持久后台服务,但它不是正确的解决方案,因为:

  • battery consumption 电池消耗
  • service termination, due to android memory management 服务终止,由于android内存管理

So I'm trying with AlarmManager. 所以我正在尝试使用AlarmManager。 It works if I set an alarm to fire in X seconds (using "set" method). 如果我将警报设置为在X秒内触发(使用“set”方法),它就可以工作。 But how can I repeat an event (using "setRepeating" method) at the top of every hour, until the alarm is canceled? 但是如何在每小时的顶部重复一次事件(使用“setRepeating”方法),直到警报被取消?

Thanks! 谢谢!

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM