Android AlarmManager在错误的时间触发

时间:2015-01-20 03:13:24

标签: android alarmmanager

我的应用程序会将AlarmManager设置为触发某些事件,并在每天中午12:00重复播放。 但是,我的客户报告警报有时会正常醒来,但有时会在其他时间醒来(例如10点/ 11点)。

以下是代码段:

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
if (calendar.get(Calendar.HOUR_OF_DAY) >= 12 && calendar.get(Calendar.MINUTE) > 0)  {
    calendar.add(Calendar.DAY_OF_MONTH, 1);
}
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.PM);
int interval = (60 * 60 * 24 * 1000);

Intent intent = new Intent(mContext, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, AlarmReceiver.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), interval, pendingIntent);

取消闹钟:

Intent intent = new Intent(mContext, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, AlarmReceiver.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);

当应用程序启动时,我的应用程序将启动警报/在其中一个活动中启用此设置。因此,我使用FLAG_UPDATE_CURRENT来确保在特定时间只触发一个任务。我的代码中是否缺少导致在错误的时间触发警报的内容?

1 个答案:

答案 0 :(得分:0)

我认为你可以用下面的简单方式做到这一点:

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 12);  // 12 PM

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        60 * 60 * 24 * 1000, pendingIntent); // Daily interval, setting RTC_WAKEUP does exact time and forces device to wake up.

希望这有帮助。