Android AlarmManager为第二天设置闹钟

时间:2014-09-25 11:45:05

标签: android calendar alarmmanager

我的应用程序在使用TimePicker指定的特定时间设置警报(24小时模式)。

我注意到,如果时间是23:00并且您设置了01:00的警报,AlarmManager将其解释为已经过去的日期。目前,我设置了如下警报:

private void setUpAlarm(int hour, int minute){
    long timeInMs = 0;
    long currentTimeInMs = 0;
    long timeDifference = 0;

    // Set up a calendar to calculate when the alarm should go off
    Calendar customCalendar = new GregorianCalendar();
    customCalendar.set(Calendar.HOUR_OF_DAY, hour);
    customCalendar.set(Calendar.MINUTE, minute);
    customCalendar.set(Calendar.SECOND, 0);
    customCalendar.set(Calendar.MILLISECOND, 0);

    Date customDate = customCalendar.getTime();

    timeInMs = customDate.getTime();
    currentTimeInMs = System.currentTimeMillis();
    timeDifference = timeInMs - currentTimeInMs;

    /*
     * If the user has entered a date that has passed (time difference is negative)
     * add 24 hours to the alarm time.
     */
    if(timeDifference < 0){
        timeInMs += 86400000;
    }

    //set the alarm
    Intent intent = new Intent(this, AlarmClockRingRing.class);
    action = PendingIntent.getActivity(this, (int)timeInMs,
            intent, 0); 
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, timeInMs, action);
    Toast.makeText(this, "One shot alarm set at " + alarmTime, Toast.LENGTH_LONG).show();
}

正如您所看到的,该应用会计算时差,如果它为负,则会设置第二天的闹钟。这会产生上述错误。如何解决?

此致

马库斯

2 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,我设法改变了我的方法,而不是使用

customCalendar.set(Calendar.HOUR_OF_DAY, hour);
customCalendar.set(Calendar.MINUTE, minute);
customCalendar.set(Calendar.SECOND, 0);
customCalendar.set(Calendar.MILLISECOND, 0);

我把它改成了

customCalendar.setTimeInMillis(System.currentTimeMillis());
customCalendar.add(Calendar.HOUR_OF_DAY, diffHours);
customCalendar.add(Calendar.MINUTE, diffMinutes);
customCalendar.set(Calendar.SECOND, 0);
customCalendar.set(Calendar.MILLISECOND, 0);

像这样获取diffHoursdiffMinutes

diffHours   = timeDifference / (60 * 60 * 1000) % 24;
diffMinutes = timeDifference / (60 * 1000) % 60;

如果用户选择了相同的当前时间,而不是过去的日期或未来的日期,则意味着他希望在24小时后触发警报:

if (timeDifference == 0) {
    diffHours = 24;
} 

如果我想管理好几天怎么办?这样做

diffDays = timeDifference / (24 * 60 * 60 * 1000);

然后将天数转换为数小时

if (diffDays != 0) {
    diffHours = diffHours + (diffDays * 24);
}

同时改变你的:

if (timeDifference < 0) {
    timeInMs += 86400000;
}

为:

if (timeDifference < 0) {
    timeDifference += 86400000;
}

你的:

am.set(AlarmManager.RTC_WAKEUP, timeInMs, action);

要:

am.set(AlarmManager.RTC_WAKEUP, customCalendar.getTimeInMillis(), action);

答案 1 :(得分:-1)

只是一张纸条......

如果您使用的不是RTC_WAKEUPRTC,则无法使用System.currentTimeMillis()

例如 ELAPSED_TIME 使用SystemClock.elapsedRealtime()

https://developer.android.com/reference/android/app/AlarmManager.html#RTC_WAKEUP