Search code examples
androidalarmmanager

Android : AlarmManager fires off for past time


This is my code for alarm manager:

Intent intent=new Intent(getBaseContext(),AlarmReciever.class);
intent.setAction("com.example.projectx.ACTION");

PendingIntent pendingIntent=PendingIntent.getBroadcast(this,12345, intent,PendingIntent.FLAG_CANCEL_CURRENT);

AlarmManager alarmManager=(AlarmManager)getSystemService(Activity.ALARM_SERVICE);

alarmManager.set(AlarmManager.RTC_WAKEUP,targetCal.getTimeInMillis(),pendingIntent);

The code works great if i select the alarm to fire off at a future hour/minute. But if I select a past hour/minute it fires up immediately as I click on "set alarm".

Example:

  • now it is 15:00 , i set the alarm for 15:45, alarm goes off at 15:45, everything ok

  • now it is 15:00 , i set the alarm for 14:30, the alarm goes off as soon as i click "set alarm"!

My time picker is always set to 24 hour mode. Could that be a problem?

Thank you!


Solution

  • Of course it does... It's meant to work so.
    Android recognizes that the time is past, so it will fire the alarm, even if it's late.

    You can make sure that the time set for the alarm is after the current time. Just calculate this difference:

    int diff = Calendar.getInstance().getTimeInMilis() - targetCal.getTimeInMillis();
    

    If diff is greater than 0, then add a day to your calendar (targetCal)
    Now, your device's time will be earlier (instead of being later) than the next scheduled alarm time.