Ashish Augustine
Ashish Augustine

Reputation: 2030

How to set multiple alarms in android

I wanted to create a birthday reminder app. I save the name of person , date of birth and a birthday message in the database . I wanted to send the message automatically on that date . Can anyone suggest an idea to do this. Can shared preference be used here? Can the specific id be passed to the database on a specific date for sending greetings to a person at his DOB. Can anyone please suggest an idea to handle multiple alarms in this case.

Upvotes: 1

Views: 1874

Answers (1)

zeetoobiker
zeetoobiker

Reputation: 2789

Ignoring the fact that there are multiple apps that can do this already (and as a disclaimer I've released an app which does exactly that) here's how I did it.

Simple Steps:

  1. Set an alarm to wake the device once a day
  2. When you receive an alarm grab a wake-lock
  3. Work out if any birthdays are going to happen today
  4. If so send / queue a message etc
  5. Set the alarm to be tomorrow

You will also need to catch the reboot of the device because any alarms will be destroyed when the device reboots. In which case simply have the intent for BOOT_COMPLETED call into the steps above at number 2.

My alarm code:

long alarmTime = System.currentTimeMillis()+(24*60*60*1000);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
Intent intent = new Intent("<package name>.WAKEUP_ALARM");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);

I actually specify a fixed point in time each day, say about 5am to wake the device and work out what might need to be done that day, but that's relatively easy to deal with (and happens elsewhere in my app for other reasons).

Whilst you could set alarms for all the birthdays over the next year it's a waste of time as all alarms are removed when the device reboots and if the user changes anything you may have to throw the alarm away anyway.

If you really want to pass a database ID through the alarm simply add it to the Intent:

Intent intent = new Intent("<package name>.WAKEUP_ALARM");
intent.putExtra("DatabaseKey", 1);

Sending the message (assuming an SMS message?) automatically requires that you have the SEND_SMS permission and you send an SMS message in the background - like this stackoverflow answer

Upvotes: 4

Related Questions