2

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?

almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
Matt Southard
  • 71
  • 1
  • 7

1 Answers1

4

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Could you explain the reason being behind "~2/3rd of the time" and that magic "08:16" time mark? :) – shkschneider Jun 11 '15 at 12:49
  • @shkschneider: The magic 8:16 comes from the code snippet in the question. The "~2/3rds" is because there are 24 hours in the day, meaning that 8:16 of today is in the past for 15 hours and 44 minutes of the day, which is about two-thirds of the day. – CommonsWare Jun 11 '15 at 12:59
  • Oh, right ;) I (wrongly) suspected a kind of easter-egg default time, but no. Thanks for the clarification and logical explaination. – shkschneider Jun 11 '15 at 13:01
  • So when setting the Calendar time as the repeating, if its past that time, it automatically goes off? So I guess I'll have to correct it so this method is only run the first time the app is open? – Matt Southard Jun 11 '15 at 13:01
  • @MattSouthard: "... it automatically goes off?" -- yes. It is up to you to set the initial date to be in the future. "So I guess I'll have to correct it so this method is only run the first time the app is open?" -- or just `add()` one day to the `Calendar`, if the originally calculated value is in the past. – CommonsWare Jun 11 '15 at 13:31