Search code examples
androidalarmmanager

Android Schedule Alarm Mon - Wed - Fri


I have read a lot of tutorials about how to set up an alarm. For my project I'm following the code provided by Google (Download the sample button @ https://developer.android.com/training/scheduling/alarms.html) however my alarm fires every time I set it. This is the code.

alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// Set the alarm to fire at approximately 6:00 p.m., according to the device's
// clock, and to repeat mon, wed, fri.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
// Set the alarm's trigger time to 2:49 p.m.
calendar.set(Calendar.HOUR_OF_DAY, 14);
calendar.set(Calendar.MINUTE, 49);
calendar.set(Calendar.SECOND, 00);
calendar.set(Calendar.MILLISECOND, 00);
int day = 2;
while(day < 7){
   //2 - monday, 4 - wednesday, 6 friday
   calendar.set(Calendar.DAY_OF_WEEK,day);
   alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,  
   calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
   day += 2;
}

Edit 1: Yesterday I noticed that this alarm is activating (besides every time I set it) every hour at the minute 49, example 14:49, 15:59, 16:49, etc.


Solution

  • Ok,

    After struggling with this one I had to do some hack due to this :

    Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.
    

    All alarms will be treated as inexact alarms, this causes that alarms fires after some random time (not what you, the programmer, decides). However this is not a big deal to me 'cause it fires 20 minutes top after the time I set it.

    ...so, I just set one (1) alarm with:

    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,  
                cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
    

    This fires an alarm every day at a random time close to what I set with cal.set(...) but on my WakefulBroadcastReceiver.onRecieve(...) I check if today's day is Monday, or Wednesday or Friday:

    @Override
    public void onReceive(Context context, Intent intent) {
    //Check if it should do stuff
        Calendar now = Calendar.getInstance();
        now.setTimeInMillis(System.currentTimeMillis());
        int day = now.get(Calendar.DAY_OF_WEEK);
    
        if(day == Calendar.MONDAY || day == Calendar.WEDNESDAY || day == Calendar.FRIDAY){        
            //Do things!
        }
        else{
            //Do nothing
        } 
    }
    

    Have a good one!