【问题标题】:How to prevent my application to get cached value of TimeZone.getDefault()?如何防止我的应用程序获取 TimeZone.getDefault() 的缓存值?
【发布时间】:2024-01-18 22:14:02
【问题描述】:

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

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

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

如何防止getDefault() 的缓存?

【问题讨论】:

    标签: android calendar timezone


    【解决方案1】:

    这并不漂亮,但您可能会调用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 - 标识新时区的 java.util.TimeZone.getID() 值。

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

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

    随后对getDefault() 的任何调用都将返回正确/更新的时区。

    【讨论】:

      最近更新 更多