Alert works immediately if the time is longer than the closed Larm

Asked

Viewed 106 times

2

This is the code I have :

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

The goal was to send a notification after 24 hours and it works after 24 hours the problem is that imagine my alarm is for 12:20 and when I trigger the alarm is 13:20 in my system it triggers the alarm so someone knows how to solve?

1 answer

1


That’s the expected behaviour of Alarmmanager.

The solution is to check, before creating the alarm, whether the time is earlier than the current time and, if yes, to add a day.

To facilitate "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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.