如何在AlarmManager的时间间隔之间设置重复警报?

时间:2018-06-19 10:57:53

标签: android android-intent calendar alarmmanager android-alarms

我需要在上午9点触发Android中的appwidgets警报。之后,闹钟应该每15分钟一次,直到上午11点,此时警报在第二天上午9点被设置为最后一次,并且循环继续。但是,我的代码一直在不停地触发警报。

protected  void scheduleNextUpdate(Context context, Intent intent, int[] allWidgetIds) {

    // set the Alarm
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    // Get all ids and store it in the intent
    // Fire the intent once the alarm happens
    intent.setAction(ACTION_APPWIDGET_UPDATE);
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
            context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Calendar at9= Calendar.getInstance();
    at9.set(Calendar.HOUR, 9);
    at9.set(Calendar.MINUTE,0);
    at9.set(Calendar.SECOND,0);
    Calendar at11 = Calendar.getInstance();
    at11.set(Calendar.HOUR, 11);
    at11.set(Calendar.MINUTE,0);
    at9.set(Calendar.SECOND,0);

    // Get a calendar instance for the actual alarm
    Calendar alarmTime = Calendar.getInstance();
    alarmTime.set(Calendar.MINUTE, 1);
    alarmTime.set(Calendar.SECOND, 0);

    if(alarmTime.after(at9) && alarmTime.before(at11)){
        alarmTime.add(Calendar.MINUTE, 15);
    }
    else if(alarmTime.after(at9) && alarmTime.after(at11)){
        alarmTime.set(Calendar.HOUR_OF_DAY, Constants.REFRESH_TIME);
        alarmTime.add(Calendar.DAY_OF_YEAR,1);
    }
    // For API 19 and later, set may fire the intent a little later to save battery,
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime.getTimeInMillis(), pendingIntent);
    } else {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime.getTimeInMillis(), pendingIntent);
    }
}

我错过了什么?

0 个答案:

没有答案