为另一个时区配置一个 AlarmManager

Configuring an AlarmManager for another timezone

我想为不同的时区配置警报管理器。我希望闹钟在 10:20 纽约时间到达时触发通知。是否可以像下面这样编码?

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);
    }

使用这个方法:

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();

}

然后将其插入 AlarmManager

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