FaisalAhmed FaisalAhmed - 3 months ago 9
Android Question

Daily alarm issue, Calendar.DATE and Calendar.DAYS_OF_MONTH difference

I am trying to implement alarm that notify daily at the same time. It works fine. But when i set alarm again it notify me on the spot without waiting time to come, because time on which alarm is set has been passed. But when I change

Calendar.DATE
to
Calendar.DAYS_OF_MONTH
it does not notify me. So can any one help me where i am wrong. I am sharing my code below.

public void setNotification() {
PendingIntent pendingIntent = createPendingIntent();

Calendar calendarToSet=Calendar.getInstance();
Calendar currentTime=Calendar.getInstance();
calendarToSet.set(Calendar.HOUR,10);
calendarToSet.set(Calendar.MINUTE,0);
calendarToSet.set(Calendar.SECOND,0);
calendarToSet.set(Calendar.AM_PM,Calendar.AM);

if(calendarToSet.before(currentTime))
{
calendarToSet.set(Calendar.DATE,1);
}


AlarmManager alarmManager = (AlarmManager) MyAppManager.context.getSystemService(Context.ALARM_SERVICE);

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendarToSet.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
// Toast.makeText(MyAppManager.context, "set", Toast.LENGTH_LONG).show();
}

public PendingIntent createPendingIntent() {
Intent intent = new Intent(MyAppManager.context, TaffaquhFiddinBroadCastReceiver.class);
intent.putExtra("key", "What_to_say_upon_completing_ablution");
PendingIntent pendingIntent = PendingIntent.getBroadcast(MyAppManager.context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;

}


What i am trying to do is to set alarm for the next day if the time is passed so please help.

Also what is the difference between
Calendar.DATE
and
Calendar.DAYS_OF_MONTH
?

Answer

The problem is you are setting the day field of your Calendar instance, instead of adding a day to it.

Change the following:

calendarToSet.set(Calendar.DATE, 1);

To this:

calendarToSet.add(Calendar.DATE, 1);

Also what is the difference between Calendar.DATE and Calendar.DAYS_OF_MONTH?

They are the same, DATE is just a synonym for DAY_OF_MONTH.

From the source code of the Calendar class:

public static final int DATE = 5;
public static final int DAY_OF_MONTH = 5;

As you can see, they represent the same value.

Comments