androidnotificationsalarmmanagerrepeatingalarm

Configuring an AlarmManager for another timezone


I would like to configure alarm manager for a different timezone. I would like the alarm to trigger a notification whenever 10:20 NY time has reached. Is it possible to code like below?

private void configureDailyAlarm(Context context) {

        TimeZone USTimeZone = TimeZone.getTimeZone("America/New_York");
        Calendar USCalendar = Calendar.getInstance(USTimeZone);
        USCalendar.set(Calendar.HOUR_OF_DAY, 10);
        USCalendar.set(Calendar.MINUTE, 20);

        Intent alarmReceiverIntent = new Intent(context, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmReceiverIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);

        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, USCalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    }

Solution

  • Use this method:

    public int getTimeFromNY() {
            TimeZone USTimeZone = TimeZone.getTimeZone("America/New_York");
            Calendar USCalendar = Calendar.getInstance(USTimeZone);
            USCalendar.set(Calendar.HOUR_OF_DAY, 10);
            USCalendar.set(Calendar.MINUTE, 20);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date()); // Current date
            return USCalendar.getTimeInMillis() - calendar.getTimeInMillis();
    
    }
    

    Then plug that into AlarmManager

    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeInMillis() + USCalendar.getTimeFromNY(), AlarmManager.INTERVAL_DAY, pendingIntent);