AlarmManager - 如何在每一个小时的顶部重复一个报警? [英] AlarmManager - How to repeat an alarm at the top of every hour?

查看:247
本文介绍了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 - 如何在每一个小时的顶部重复一个报警?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆