AlarmManager - 如何在每一个小时的顶部重复一个报警?小时、如何在、AlarmManager

2023-09-12 22:52:29 作者:去哪儿@

我要为一个触发事件,每隔一小时(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);