0

Background

I am using AlarmManager to Display Notification every day at 11 am.

Code

mAlarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(appContext, AlarmReciever.class);
// Create a PendingIntent to be triggered when the alarm goes off
pIntent = PendingIntent.getBroadcast(appContext, AlarmReciever.REQUEST_CODE,
                    intent, PendingIntent.FLAG_CANCEL_CURRENT);
// Set the alarm to start at approximately 11:00 a.m.
Calendar alarmCal = Calendar.getInstance();
alarmCal.setTimeInMillis(System.currentTimeMillis());
alarmCal.set(Calendar.HOUR_OF_DAY, 11);
// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
Log.d("TIME IN MILLI", String.valueOf(alarmCal.getTimeInMillis()));
mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmCal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pIntent);
setBootRecieverEnabled(); 

Issue:

The Alarm gets fired after a short while when I set the alarm in App.

omer
  • 522
  • 1
  • 8
  • 26

1 Answers1

0

I have found the solution here.

We need to increment alarm date if the time we are setting is passed.

mAlarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(appContext, AlarmReciever.class);
// Create a PendingIntent to be triggered when the alarm goes off
pIntent = PendingIntent.getBroadcast(appContext, AlarmReciever.REQUEST_CODE,
                    intent, PendingIntent.FLAG_CANCEL_CURRENT);
// Set the alarm to start at approximately 11:00 a.m.
Calendar alarmCal = Calendar.getInstance();
alarmCal.setTimeInMillis(System.currentTimeMillis());
alarmCal.set(Calendar.HOUR_OF_DAY, 11);

Solution - Increment date in alarm calendar

if(now.after(alarmCal)){
    alarmCal.add(Calendar.DATE, 1);
}

...

// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
Log.d("TIME IN MILLI", String.valueOf(alarmCal.getTimeInMillis()));
mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmCal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pIntent);
setBootRecieverEnabled();

Google should have mentioned this in the docs.

omer
  • 522
  • 1
  • 8
  • 26