使用案例:记录显示给用户的错误消息.
但是,您不希望日志中的消息依赖于用户设备的区域设置.另一方面,您不希望仅为您的(技术)日志记录更改用户设备的区域设置.这可以实现吗?我在stackoverflow上找到了几个可能的解决方案:
但是,它们都会导致更改设备的区域设置(直到下一次配置更改).
无论如何,我目前的解决方法是这样的:
public String getStringInDefaultLocale(int resId) {
Resources currentResources = getResources();
AssetManager assets = currentResources.getAssets();
DisplayMetrics metrics = currentResources.getDisplayMetrics();
Configuration config = new Configuration(
currentResources.getConfiguration());
config.locale = DEFAULT_LOCALE;
/*
* Note: This (temporiarily) changes the devices locale! TODO find a
* better way to get the string in the specific locale
*/
Resources defaultLocaleResources = new Resources(assets, metrics,
config);
String string = defaultLocaleResources.getString(resId);
// Restore device-specific locale
new …Run Code Online (Sandbox Code Playgroud)