alarmmanager立即启动

时间:2017-12-11 14:12:31

标签: android alarmmanager

我想在星期几的每周设置闹钟,这是我的代码:

int notificationId = getNotificationId(); //it get a random number
Context context = rule.context;
Intent intent = ((Activity) context).getIntent();
long time = getRuleCalendar().getTimeInMillis();
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
     notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
     alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
     alarmManager.setExact(AlarmManager.RTC_WAKEUP, time,pendingIntent);
} else {
  alarmManager.set(AlarmManager.RTC_WAKEUP, time,pendingIntent);
}

public calendar getRuleCalendar(){
    Calendar calSet = Calendar.getInstance();
    calSet.set(Calendar.DAY_OF_WEEK, calendarDay); //calendarDay change by day of weeks
    calSet.set(Calendar.HOUR_OF_DAY, 0);
    calSet.set(Calendar.MINUTE, 0);
    calSet.set(Calendar.SECOND, 0);
    calSet.set(Calendar.MILLISECOND, 1);
    return calSet
}

现在我的问题是一个警报立即启动(现在是在夜间之后,我今天想检查它是好的)但所有其他警报在错误的时间开始。 为什么呢?

1 个答案:

答案 0 :(得分:1)

如果您过去设置闹钟,闹钟只会立即触发。 例如,在您的情况下,您将在今天00:00 AM设置闹钟,这是今天的过去日期。 因此,您已设置为第二天00:00 AM设置闹钟。为此,只需在 Calendar.DAY_OF_YEAR 中添加1。

 public Calendar getRuleCalendar(){
    Calendar calSet = Calendar.getInstance();
    calSet.set(Calendar.HOUR_OF_DAY, 0);
    calSet.set(Calendar.MINUTE, 0);
    calSet.set(Calendar.SECOND, 0);
    calSet.add(Calendar.DAY_OF_YEAR,1);
    calSet.set(Calendar.MILLISECOND, 1);
    return calSet;
}

设置重复闹钟你需要查看Documentation

如果您不知道从Android M开始的打盹模式中的背景行为更改,那么请查看Optimizing for Doze and App Standby