3

I'm building a reminders application where one time, weekly, monthly reminders and we notify the user of the reminder on due date and time. Reminders can be updated any time by the user to update the reminding time or delete the reminder altogether. I have thought of two ways I can solve the particular problem.

  1. Whenever user sets a reminder, schedule an alarm accordingly with an unique Id and update or delete it in case user updates or deletes the alarm.
  2. Since I store the reminding time in DB, better approach would be to schedule an alarm for the nearest reminder. And have the Service which is triggered by the alarm schedule a new alarm for the next nearest reminder.

2nd approach seems clean approach but how do we tackle the case where the Service triggered by alarm gets killed by the system before it schedules a new alarm for the next reminder?

Edit Looks like if the system kills a Service for memory, it will re-create the Service. Does it mean it is safe to rely on the Service to schedule alarm every time it is run?

Edit 2 I've realized that Android kills any alarms whenever the device is restarted. This makes approach 2 a better solution. I've implemented it for now.

Gautham
  • 3,418
  • 3
  • 30
  • 41
  • Why not use standard Android Calendar reminders? http://stackoverflow.com/questions/5976098/how-to-set-reminder-in-android – vasart Jul 09 '12 at 10:55
  • That would require calendar permission which I'm not inclined to have in the app. Is it possible to have custom behavior when the user selects on the notification through standard calendar reminders? – Gautham Jul 09 '12 at 11:04

1 Answers1

1

The pending intent needs to be created exactly in the same way for canceling the already set alarm. You can cancel previous alarm when you set a new alarm, if you want to have a single alarm activated at some time.

For setting alarm use:

Intent myIntent = new Intent(getApplicationContext(), SessionReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

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

alarmManager.set(AlarmManager.RTC, now.getTimeInMillis(), pendingIntent);

For canceling the alarm use:

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent myIntent = new Intent(getApplicationContext(), SessionReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

alarmManager.cancel(pendingIntent);
DjSh
  • 2,776
  • 2
  • 19
  • 32