Search code examples
androidalarmmanager

Why my Alarm is fired earlier than my set time?


I'm currently trying to make an alarm app that will mute all audio volume at the user-defined day and time. However, the alarm seems not fired at the correct time. I found that the alarm is always fired earlier.

This is my set alarm code:

public static void setAlarm(Context context, String time, int day, int reqCode) {
    String[] timeSplit = time.split(":");
    Calendar calendar = Calendar.getInstance();

    int hour = Integer.parseInt(timeSplit[0]);
    int minute = Integer.parseInt(timeSplit[1]);
    int days = (day-calendar.get(Calendar.DAY_OF_WEEK) + calendar.get(Calendar.DAY_OF_MONTH));

    calendar.set(
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            days,
            hour,
            minute,
            0
    );

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, RuleAlarm.class);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, reqCode, intent, 0);

    // Set the alarm to be fired every week on the selected day
    alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 7 * 24 * 60 * 60 * 1000, pendingIntent);

    Toast.makeText(context, "Alarm is set", Toast.LENGTH_SHORT).show();
}

I have tried to change setRepeating() to setInexactRepeating() but nothing changed.


Solution

  • I finally find out the problem. It lies on the day params. What I pass to day params is my Spinner selected position which starts from zero while the Calendar days starts from one (SUNDAY = 1, MONDAY = 2, so on). So, the alarm will always be set in the past days. I plus one to the day params and it's worked.

    This is my piece of code where the startAlarm() function got called.

    String ruleStartTime = rule_startTime.getText().toString();
    
    // Spinner index starts from zero,
    // to match with the Calendar day indexing, we need to plus it one
    int dayIdx = day.getSelectedItemPosition()+1;
    
    Alarm.setAlarm(getApplicationContext(), ruleStartTime,
                            dayIdx, 0);