AlarmManager警报无法在分钟更改时完全启动

时间:2016-09-27 12:04:08

标签: android alarmmanager

我正在做一个闹钟,虽然使用精确的闹钟,但它并不是从分钟的变化开始的:

例如我设置在7:30它将在7:30:00 - 7:31之间的某个地方开始(无法检查确切的时间)。

我这样叫警报:

// Create the alarm
CustomAlarmManager alarmManager = new CustomAlarmManager(getActivity());
alarmManager.scheduleRepeatingAlarm(getActivity(), alarmID, alarmHour, alarmMinute);

运行此功能以创建警报:

public void scheduleRepeatingAlarm(Context context, int alarmID, int alarmHour, int alarmMinute) {

    // Create an intent to go to the notifications reciever class
    Intent intent = new Intent(context, AlarmNotificationReciever.class);

    // Bundle information and add to the intent for use later
    Bundle extras = new Bundle();
    extras.putInt("AlarmId", alarmID);
    extras.putInt("AlarmHour", alarmHour);
    extras.putInt("AlarmMinute", alarmMinute);
    intent.putExtras(extras);

    // Create a pending intent for the alarm id and intent
    PendingIntent pIntent = PendingIntent.getBroadcast(context,
            alarmID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    // Create a calender variable with the time for the alarm
    Calendar calender = Calendar.getInstance();
    calender.set(Calendar.HOUR_OF_DAY, alarmHour);
    calender.set(Calendar.MINUTE, alarmMinute);

    // Create a variable for the current alarm time
    LocalTime currentAlarmTime = LocalTime.parse(alarmHour+":"+alarmMinute+":"+"00");

    // Create a variable for the local time
    LocalTime localDeviceTime = LocalTime.now();

    // If the alarm has already elapsed today add one day to it so it runs for tomorrow
    if (localDeviceTime.isAfter(currentAlarmTime)) {

        calender.add(Calendar.DATE, 1);
        System.out.println("The time of day for the alarm has already past rescheduling for tomorrow");
    }

    // For the different versions of operating system set off a single shot alarm
    if(Build.VERSION.SDK_INT >= 23) {
        mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
                calender.getTimeInMillis(), pIntent);
    } else if(Build.VERSION.SDK_INT >= 19) {
        mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(), pIntent);
    } else {
        mAlarmManager.set(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(), pIntent);
    }
}

我假设这个问题与这些问题一致:

Calendar calender = Calendar.getInstance();
calender.set(Calendar.HOUR_OF_DAY, hour);
calender.set(Calendar.MINUTE, minute);

设置闹钟时的这一行:

mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(), pIntent);

但我不确定为什么那不会完全取决于分钟的变化。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

Calendar.getInstance()会将Calendar个实例设置为当前时间(和日期)。

您正在设置此HOUR_OF_DAY个实例的MINUTECalendar字段,但SECOND字段仍有其初始值,这是导致这种行为。

更改以下内容:

Calendar calender = Calendar.getInstance();
calender.set(Calendar.HOUR_OF_DAY, hour);
calender.set(Calendar.MINUTE, minute);

对此:

Calendar calender = Calendar.getInstance();
calender.set(Calendar.HOUR_OF_DAY, hour);
calender.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);