AlarmManager在设置警报后立即触发警报

时间:2017-10-19 09:21:18

标签: push-notification alarmmanager

背景

我每天上午11点使用AlarmManager来显示通知。

代码

mAlarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(appContext, AlarmReciever.class);
// Create a PendingIntent to be triggered when the alarm goes off
pIntent = PendingIntent.getBroadcast(appContext, AlarmReciever.REQUEST_CODE,
                    intent, PendingIntent.FLAG_CANCEL_CURRENT);
// Set the alarm to start at approximately 11:00 a.m.
Calendar alarmCal = Calendar.getInstance();
alarmCal.setTimeInMillis(System.currentTimeMillis());
alarmCal.set(Calendar.HOUR_OF_DAY, 11);
// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
Log.d("TIME IN MILLI", String.valueOf(alarmCal.getTimeInMillis()));
mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmCal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pIntent);
setBootRecieverEnabled(); 

问题:

当我在App中设置闹钟时,闹钟会在一段时间后被触发。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案here

如果我们设置的时间过去,我们需要增加闹钟日期。

mAlarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(appContext, AlarmReciever.class);
// Create a PendingIntent to be triggered when the alarm goes off
pIntent = PendingIntent.getBroadcast(appContext, AlarmReciever.REQUEST_CODE,
                    intent, PendingIntent.FLAG_CANCEL_CURRENT);
// Set the alarm to start at approximately 11:00 a.m.
Calendar alarmCal = Calendar.getInstance();
alarmCal.setTimeInMillis(System.currentTimeMillis());
alarmCal.set(Calendar.HOUR_OF_DAY, 11);

解决方案 - 报警日历中的增量日期

if(now.after(alarmCal)){
    alarmCal.add(Calendar.DATE, 1);
}

...

// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
Log.d("TIME IN MILLI", String.valueOf(alarmCal.getTimeInMillis()));
mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmCal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pIntent);
setBootRecieverEnabled();

Google应该在文档中提到这一点。