如何防止我的应用程序获取 TimeZone.getDefault() 的缓存值?

How to prevent my application to get cached value of TimeZone.getDefault()?

我正在使用 TimeZone.getDefault() 设置 Calendar 的时区 class:

Calendar cal = Calendar.getInstance(TimeZone.getDefault());
Log.i("TEST", cal.get(Calendar.HOUR) + ":" + cal.get(Calendar.MINUTE));

但是,当用户从“设置”更改他们设备的时区时,我的应用程序表示使用前一个时区的时间,直到他们强制停止(从应用程序信息设置)应用程序和重新启动它。

如何防止 getDefault() 的缓存?

它并不漂亮,但您可以调用 setDefault(null) 来显式擦除缓存值。根据 the documentation,这只会影响当前进程(即您的应用)。

清空缓存值后,下次调用 getDefault() 时,会重新构造该值:

/**
 * Returns the user's preferred time zone. This may have been overridden for
 * this process with {@link #setDefault}.
 *
 * <p>Since the user's time zone changes dynamically, avoid caching this
 * value. Instead, use this method to look it up for each use.
 */
public static synchronized TimeZone getDefault() {
    if (defaultTimeZone == null) {
        TimezoneGetter tzGetter = TimezoneGetter.getInstance();
        String zoneName = (tzGetter != null) ? tzGetter.getId() : null;
        if (zoneName != null) {
            zoneName = zoneName.trim();
        }
        if (zoneName == null || zoneName.isEmpty()) {
            try {
                // On the host, we can find the configured timezone here.
                zoneName = IoUtils.readFileAsString("/etc/timezone");
            } catch (IOException ex) {
                // "vogar --mode device" can end up here.
                // TODO: give libcore access to Android system properties and read "persist.sys.timezone".
                zoneName = "GMT";
            }
        }
        defaultTimeZone = TimeZone.getTimeZone(zoneName);
    }
    return (TimeZone) defaultTimeZone.clone();
}

您可能应该将其与 ACTION_TIMEZONE_CHANGED 的广播侦听器结合使用,并且仅在收到此类广播时才取消默认值。


编辑:想想看,一个更简洁的解决方案是从广播中提取新设置的时区。来自广播文档:

time-zone - The java.util.TimeZone.getID() value identifying the new time zone.

然后您可以简单地使用此标识符来更新缓存的默认值:

String tzId = ...
TimeZone.setDefault(TimeZone.getTimeZone(tzId));

随后对 getDefault() 的任何调用都将 return correct/updated 时区。