0

I want to trigger a daily alarm in my application. I can see the alarm being triggered daily at the correct time for 2 or 3 days but it does not trigger after that. For example if I set alarm to trigger at 08:00 AM, it will trigger at 8 AM daily for 2 or 3 days and after that there is no alarm triggered. There is no app crashing or anything, it simply does not trigger. I have a BroadcastReceiver registered (in AndroidManifest.xml) for this alarm and i can see logs being printed daily at the correct time but only for 2 or 3 days. After that there is no activity and the app just seems to die down.

Please find my code below :

final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
final long intervalDay = 60*60*24*1000L;
final long alarmTime = calendar.getTimeInMillis();
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, intervalDay, pendingIntent);

I have also used alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, AlarmManager.INTERVAL_DAY, pendingIntent); but it did not make any difference (didnt expect it to make any though).

I do not want to use alarmManager.setInexactRepeating() as it does not trigger the alarm at exact time but there is slight delay.

Any help appreciated !!

Thanks.

void
  • 187
  • 1
  • 3
  • 13

1 Answers1

0

That's because android cannot hold the alarm content for more than 2-3 days. Though there is no sure shot solution that i know.

I fixed it by cancelling and resetting alarm everytime alarm is triggered. Something like this. Instead of using setRepeat use set or setExact to trigger for once:

if(android.os.Build.VERSION.SDK_INT<Build.VERSION_CODES.KITKAT) {
    alarmManager.set(AlarmManager.RTC_WAKEUP, alarmtime, pendingIntent);
} else {
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmtime, pendingIntent);
}

Then in onRecieve() method of your alarmReciever after performing your task, reset the alarm again for next followed by cancelling all pending intents:

PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), reminderModal.get_remindID(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();

Hope it helps.

Dhruv
  • 1,801
  • 1
  • 15
  • 27
Ibrahim Gharyali
  • 544
  • 3
  • 22
  • can you please tell me what to write in OnRecieve method for canceling and resetting alarm and do I need to call this method after calling Alarm screen? – Saloni Parikh Aug 04 '20 at 09:07