Android guide to setting a single or repeating alarm

If you are developing an app which deals with alarms, you might be confused as to how to set either a single alarm or a repeating alarm, I will walk you through it so you can get a better understanding of how it works.

In this example, we will say we are trying to create an alarm that triggers some piece of code at 8:30 AM, either once or repeating everyday.
Use this code snippet wherever it is that you want to create your alarm.

AlarmManager alarmMgr = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
Intent receiverIntent = new Intent(c, WakeupReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(c, 0, receiverIntent, 0); //The second parameter is unique to this PendingIntent,
                                                                                 //if you want to make more alarms, 
                                                                                 //make sure to change the 0 to another integer
int hour = 8;
int minute = 30;

Calendar alarmCalendarTime = Calendar.getInstance(); //Convert to a Calendar instance to be able to get the time in milliseconds to trigger the alarm
alarmCalendarTime.set(Calendar.HOUR_OF_DAY, hour);
alarmCalendarTime.set(Calendar.MINUTE, minute);
alarmCalendarTime.set(Calendar.SECOND, 0); //Must be set to 0 to start the alarm right when the minute hits 30

//Add a day if alarm is set for before current time, so the alarm is triggered the next day
if (alarmCalendarTime.before(Calendar.getInstance())) {
   alarmCalendarTime.add(Calendar.DAY_OF_MONTH, 1);

alarmMgr.set(AlarmManager.RTC_WAKEUP, alarmCalendarTime.getTimeInMillis(), alarmIntent);

Continue reading