Search code examples
androidtimezonealarmmanagerandroid-broadcastdst

Android AlarmManager scheduling through time zone or daylight shifts


I have a logic that schedules reminders using AlarmManager. I need to implement the following:

Logic 1: when the user changes time zone, eg he travels from UK (UTC+0) to central Europe (UTC+1), alarms should follow the time zone. Example, a reminder scheduled at 3PM UTC+0 should fire at 4PM UTC+1

Logic 2: when a time shift occurs, eg time shifts to daylight saving time in spring (from UTC+1 to UTC+2), alarms should keep the original time Example, a reminder scheduled at 3PM UTC+1 should fire at 3PM UTC+2

How can I achieve this? As of now I have no particular logic in place and all the alarms follow Logic 1. I have found no way to identify when a time shift happens.

Scheduling logic is very simple:

LocalDateTime reminderTime = LocalDateTime.of(...)
ZoneOffset currentOffsetForMyZone = ZoneId.systemDefault().getRules().getOffset(Instant.now());
reminderTime.toInstant(currentOffsetForMyZone).toEpochMilli();
alarmManager.setExact(AlarmManager.RTC_WAKEUP, reminderTime, pendingIntent);

Solution

  • If anyone is interested, the fix was to apply the correct offset for the date and time where the alarm is to go of, as pointed out by Ole. My silly mistake was to apply always the current timezone.

    LocalDateTime alarmTime = LocalDateTime.of(...)
    ZoneId zone = ZoneId.systemDefault();
    ZonedDateTime zoneDateTime = ZonedDateTime.of(alarmTime , zone);
    long startAtMillis = zoneDateTime.toInstant().toEpochMilli();
    //Fire alarm
    notificationAlarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, startAtMillis, pendingIntent);