如何在设置闹钟之前检查闹钟时间是否已经过去?

时间:2014-06-05 10:06:32

标签: android alarmmanager android-alarms

我尝试了以下以毫秒为单位检查当前时间的闹钟时间的方法,在大多数情况下它的工作正常,但是当我为例如设置闹钟时。 @ 4:07下午(即完全小时后几分钟)然后比较失败..

operation_morn = PendingIntent.getBroadcast(getBaseContext(), RQS_morn,
                intent, 0);
        Calendar calNow = Calendar.getInstance();
        long current_time = calNow.getTimeInMillis();
        // Calendar calSet = (Calendar) calNow.clone();
        // calNow.set(selected_Year, selected_Month, selected_Day);
        calNow.set(Calendar.DAY_OF_MONTH, selected_Day);
        calNow.set(Calendar.MONTH, (selected_Month - 1));
        calNow.set(Calendar.YEAR, selected_Year);
        calNow.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hours));
        calNow.set(Calendar.MINUTE, Integer.parseInt(minutes));
        calNow.set(Calendar.AM_PM, Calendar.AM);



        long alarm_time_in_millis = calNow.getTimeInMillis();
        if (alarm_time_in_millis > current_time) {
            alarmManager.set(AlarmManager.RTC_WAKEUP, calNow.getTimeInMillis(),
                    operation_morn);

        }

1 个答案:

答案 0 :(得分:3)

问题在这里

calNow.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hours)); // It sets hour for 24 hours format.

这应该是

calNow.set(Calendar.HOUR, Integer.parseInt(hours));

这是错误的,因为您通过calNow.set(Calendar.AM_PM, Calendar.AM)将AM / PM设置为自己。如果您正在处理24小时格式,请仅删除此行。这将解决您的问题。


对于时间比较,你可以使用Timestamp,它有两次比较的方法。虽然您也可以使用Calender来比较时间。

Timestamp alramTimeStamp = new Timestamp(calNow.getTimeInMillis());
Timestamp currentTimeStamp = new Timestamp(current_time);
if (alramTimeStamp.after(currentTimeStamp)) {
    alarmManager.set(AlarmManager.RTC_WAKEUP, calNow.getTimeInMillis(),
            operation_morn);
}