如何设置闹钟在固定时间正确触发? [英] How to set an alarm to fire properly at fixed time?
问题描述
我有这个代码
Calendar c = new GregorianCalendar();
c.add(Calendar.DAY_OF_YEAR, 1);
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 22);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
// We want the alarm to go off 30 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
firstTime += 30*1000;
long a=c.getTimeInMillis();
// Schedule the alarm!
AlarmManager am = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
c.getTimeInMillis(), 1*60*60*1000, sender);
不在23:22h
我做错了什么?我注意到 firstTime 和 c.getTimeInMillis() 在大小和长度上有很大不同.当我使用firstTime时,所以当设置为30秒时,警报执行得很好.
What I am doing wrong? I noticed firstTime and c.getTimeInMillis() differs a lot in size and length. When I use firstTime, so when set to 30 seconds, the alarm is executed well.
推荐答案
您使用的是 AlarmManager.ELAPSED_REALTIME_WAKEUP
标志,但您使用的是日历对象.这两件事不能放在一起.
You are using the AlarmManager.ELAPSED_REALTIME_WAKEUP
flag, but you are using a Calendar object. These two things don't go together.
您需要使用 AlarmManager.RTC 或 AlarmManager.RTC_WAKEUP
如果您使用日历或日期对象(自 1970 年以来的毫秒数)指定闹钟时间.
You need to use AlarmManager.RTC or AlarmManager.RTC_WAKEUP
if you are specifying the alarm time using a Calendar or Date object (milliseconds since 1970).
当您通过 SystemClock.elapsedRealtime()
指定闹钟时间时,您使用 AlarmManager.ELAPSED_REALTIME
或 AlarmManager.ELAPSED_REALTIME_WAKEUP
(自手机开机).
You use AlarmManager.ELAPSED_REALTIME
or AlarmManager.ELAPSED_REALTIME_WAKEUP
when you are specifying the alarm time via SystemClock.elapsedRealtime()
(milliseconds since the phone booted).
这篇关于如何设置闹钟在固定时间正确触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!