Search code examples
androidalarmmanagerandroid-calendar

Calendar.Month in Android


I am try to set an alarm to trigger a service every 12 months.

so I tried the following:

Calendar calendar = Calendar.getInstance();
calendar.set(calendar.MONTH, calendar.get(Calendar.MONTH) + 12);
Log.e("calendar", "= " + Calendar.MONTH + " " + calendar.get(Calendar.MONTH) + 10);

long sdl = calendar.getTimeInMillis();
Intent myIntent = new Intent(mContext,
AlarmAlertBroadcastReciever.class);

PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = (AlarmManager) mContext
                .getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, sdl, pendingIntent);

The above is not triggering every 12 months, I tried every 10 months it triggered? How?


Solution

  • If you want something to be triggered every twelve month then add a year to Calendar instance. Something like this -

    calendar.add(calendar.YEAR, 1);
    

    Also, if you really want to stick with adding months this is the solution -

    calendar.add(calendar.MONTH, 12);
    

    Note - I am using add() not set().

    Hope it helps.