Search code examples
androidalarmmanager

how to set alarm to repeat monthly


Currently I am working on an application to set reminders on monthly basis. I am not able to provide the correct repeating interval for my alarmmanager. Pls provide info about the same. this is my code, but this will not raise alarm for Feb or months having 30 days. Also pls provide code to set yearly repeating alaram.

repeatTime=(AlarmManager.INTERVAL_DAY*31);
mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, when.getTimeInMillis(), repeatTime, pi);

Thanks, Sharath


Solution

  • this is how you calculate interval between today in extacly one month after, use this logic to reset alarm everytime once it triggers. i.e set alarm to the point when you want to start, supply some pending intent, once alarm triggers use below code to get next trigger time, and set alarm again to trigger at that time.

    private long getDuration(){
        // get todays date
        Calendar cal = Calendar.getInstance();
        // get current month
        int currentMonth = cal.get(Calendar.MONTH);
    
        // move month ahead
        currentMonth++;
        // check if has not exceeded threshold of december
    
        if(currentMonth > Calendar.DECEMBER){
            // alright, reset month to jan and forward year by 1 e.g fro 2013 to 2014
            currentMonth = Calendar.JANUARY;
            // Move year ahead as well
            cal.set(Calendar.YEAR, cal.get(Calendar.YEAR)+1);
        }
    
        // reset calendar to next month
        cal.set(Calendar.MONTH, currentMonth);
        // get the maximum possible days in this month
        int maximumDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    
        // set the calendar to maximum day (e.g in case of fEB 28th, or leap 29th)
        cal.set(Calendar.DAY_OF_MONTH, maximumDay);
        long thenTime = cal.getTimeInMillis(); // this is time one month ahead
    
    
    
        return (thenTime); // this is what you set as trigger point time i.e one month after
    
    }