Alert works immediately if the time exceeds the defined alarm

2

This is the code I have:

  alarme.setRepeating(AlarmManager.RTC_WAKEUP, horas, 86400000, alarmIntent);

The purpose was to send a notification after 24 hours and it works after 24 hours the problem is that we imagine my alarm is at 12:20 and I when the alarm goes off it is 13:20 on my system it triggers the alarm soon, Does anyone know how to solve it?

    
asked by anonymous 20.06.2016 / 16:14

1 answer

1

This is the expected behavior for AlarmManager.

The solution is to verify, before creating the alarm, if the time is earlier than the current time and, if so, add a day.

To facilitate "the accounts" we will use the class Calendar :

//Cria um Calendar para a hora do alarme
Calendar horaAlarme = Calendar.getInstance();
//Seta a hora do alarme
horaAlarme.set(Calendar.HOUR_OF_DAY, 12);
//Seta os minutos do alarme
horaAlarme.set(Calendar.MINUTE, 20);
//Coloca zero nos segundos
horaAlarme.set(Calendar.SECOND, 0);

//Cria um Calendar com a data/hora actual
Calendar horaActual = Calendar.getInstance();

//Adiciona um dia caso a hora actual for superior à do alarme(12:20)
if(horaActual.getTimeInMillis() >= horaAlarme.getTimeInMillis()){
    horaAlarme.add(Calendar.DAY_OF_MONTH, 1);
}

//Agenda o Alarme
alarme.setRepeating(AlarmManager.RTC_WAKEUP, 
                    horaAlarme.getTimeInMillis(),
                    AlarmManager.INTERVAL_DAY, 
                    alarmIntent);
    
20.06.2016 / 16:58