gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:54:27 26 4
gpt4 key购买 nike

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

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() 的任何调用都将返回正确/更新的时区。

关于android - 如何防止我的应用程序获取 TimeZone.getDefault() 的缓存值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30126454/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com