Set Repeat days of week alarm in android

TheDevMan picture TheDevMan · Jul 27, 2013 · Viewed 32.3k times · Source

Can somebody give good logic for set repeat days of week alarm? I have done weekly Alarm by using

            alarmCalendar.set(Calendar.HOUR, AlarmHrsInInt);
            alarmCalendar.set(Calendar.MINUTE, AlarmMinsInInt);
            alarmCalendar.set(Calendar.SECOND, 0);
            alarmCalendar.set(Calendar.AM_PM, amorpm);

            Long alarmTime = alarmCalendar.getTimeInMillis();

Intent intent = new Intent(Alarm.this, AlarmReciever.class);
                intent.putExtra("keyValue", key);
                PendingIntent pi = PendingIntent.getBroadcast(Alarm.this, key, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                am.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 7*1440*60000 , pi); 

The alarm trigger on time and after 7 days it automatically triggers at that time.

But my requirement is I want to choose days rather than just 7 days.

something like every Monday, Tuesday, Thursday at 9:00 AM - Alarm should trigger automatically. How do I go about doing this in setRepeating.

Can somebody help me out with this?

Thanks!

Answer

Shobhit Puri picture Shobhit Puri · Jul 27, 2013

These questions talk about the same thing as you want. Those answers will be helpful:

You just need to specify the day to start it and then repeat it every 7 days. There are few ways specified in answers on given questions:

How can i get the repeat alarm for week days using alarm manager?

Android Notification on specific weekday goes off directly

how to repeat alarm week day on in android

Update:

In your comment you said

How to set the triggerAtMillis part in setRepeating. say for example today is Tuesday, I choose weekly Monday, Wednesday, Friday. - What do I put for Wednesday ?

What I understood that that if today is Tuesday, how to set alarm for lets say Wednesday repeating, right? First of all yes you can use mulltiple id's to set alarms for each day separately.

Then you can add alarmCalendar.set(Calendar.DAY_OF_WEEK, week); line to your existing code. Based on the week day( from 1-7) it repeats for that day. You can pass it into a function as parameter. Like:

    setAlarm(2); //set the alarm for this day of the week

    public void setAlarm(int dayOfWeek) {
        // Add this day of the week line to your existing code
        alarmCalendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);

        alarmCalendar.set(Calendar.HOUR, AlarmHrsInInt);
        alarmCalendar.set(Calendar.MINUTE, AlarmMinsInInt);
        alarmCalendar.set(Calendar.SECOND, 0);
        alarmCalendar.set(Calendar.AM_PM, amorpm);

        Long alarmTime = alarmCalendar.getTimeInMillis();
        //Also change the time to 24 hours.
        am.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 24 * 60 * 60 * 1000 , pi); 
}

I've taken the example from one of above question. Hope its more clear now.