Search code examples
androidnotificationsalarmmanager

AlarmManager to fire notification at every 24 hours




I am using AlarmManager() to fire Notification. I am setting it to fire at 10:30 AM of the morning and repeat at every 24 hours.

My code is as follow. I have tested yesterday and the problem is that It was repeated around 4-5 times in just next 2 hours. I am not understanding that what is the problem. I want to fire it only at 10:30 AM of the morning and repeat at only 24 hours.

Please help me solve the problem. I am calling this code on my app's Splash screen onCreate()

My Code :

Intent myIntent = new Intent(Splash.this, AlarmReceiver.class);

PendingIntent pendingIntent = PendingIntent.getBroadcast(Splash.this,
        0, myIntent, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

Calendar firingCal = Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();

firingCal.set(Calendar.HOUR_OF_DAY, 10);
firingCal.set(Calendar.MINUTE, 30);
firingCal.set(Calendar.SECOND, 0);

long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();

if (intendedTime >= currentTime) {
    alarmManager.setRepeating(AlarmManager.RTC, intendedTime,
            AlarmManager.INTERVAL_DAY, pendingIntent);

} else {
    firingCal.add(Calendar.DAY_OF_MONTH, 1);
    intendedTime = firingCal.getTimeInMillis();

    alarmManager.setRepeating(AlarmManager.RTC, intendedTime,
            AlarmManager.INTERVAL_DAY, pendingIntent);
}

Solution

  • You can use CommonsWare cwac-wakeful library. It has an inbuilt support to set alarms.