I have tried the below method of checking the alarm time with the current time in millis,its working fine in most of the cases but when i set the alarm for eg. @4:07 p.m(i.e just few mins after exact hour) then the comparison fails..
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);
}
Problem is here
calNow.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hours)); // It sets hour for 24 hours format.
This should be
calNow.set(Calendar.HOUR, Integer.parseInt(hours));
This is wrong because your are setting AM/PM your self by doing calNow.set(Calendar.AM_PM, Calendar.AM)
. If you are handling 24 hours format then remove this line only. This will solve your problem.
And for time comparison you can use Timestamp
, which having method to compare two times. Although you can use Calender
also to compare times.
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);
}