Search code examples
androidalarmmanager

AlarmManager fires alarm immediately (while it shouldn't)


I have a scheduleAlarm class which is supposed to set the alarm in a specific time, however the alarm is being fired immediately after the method is called. I've checked that provided time in milliseconds is fine, so I've no idea what's going on.

private void scheduleAlarm(int day, int startHour, int startMinute, String info) {

    AlarmManager mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    Calendar c = Calendar.getInstance();

    c.set(Calendar.DAY_OF_WEEK, day);
    c.set(Calendar.HOUR, startHour);
    c.set(Calendar.MINUTE, startMinute);

    Intent startIntent = new Intent(this, Recorder.class);
    startIntent.putExtra("info", "someinfo");

    Log.v("millis", String.valueOf(c.getTimeInMillis())); // time is okay
    Random mRandom = new Random();
    int randomInt = mRandom.nextInt();

    PendingIntent pendingIntent = PendingIntent.getService(this, randomInt, startIntent,PendingIntent.FLAG_UPDATE_CURRENT);
    mAlarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
}

Solution

  • Just make sure that the time set for the alarm is after current time.

    There is an easy way to check that.

    just do

    Calendar.getInstance().getTimeInMilis() - c.getTimeInMillis()
    

    Log this result, and you can see if the second is before the first. Lets say now is 4 o'clock, and you set the same day and 3 o'clock. it will get activated instantly.

    Other than that i see no reason why it should fail.

    Another way to test would be to use currentTime and add lets say 10k miliseconds and see if it activates in 10 seconds after you test it. Then you are sure that the time set is wrong in your case.