AlarmManager going off whenever app opens

92 views Asked by At

I am trying to set an AlarmManager to go off for a specific time during the day. Here is my current code on it -

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 16);
calendar.set(Calendar.SECOND, 0);

long time = calendar.getTimeInMillis();
Intent intent = new Intent(MainActivity.this, Drawing.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
        MainActivity.this, 0, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

am.setRepeating(AlarmManager.RTC_WAKEUP, time,
        AlarmManager.INTERVAL_DAY, pendingIntent);

The drawing class displays a notification. The alarm does go off at the right time, but anytime the app is re-opened the notification goes off immediately.

I know its nothing to do with the drawing class because when i set the alarm to just go off with System.currentTimeInMillis() + 10 secs it works fine, even when app is reopening.

Any ideas? What is wrong with my logic?

1

There are 1 answers

5
CommonsWare On BEST ANSWER

You are not checking to see if calendar is in the past, as it will be ~2/3rds of the time (i.e., any time this code is run after 08:16). You will need to add() a day in that case, to get 8:16 for tomorrow.