Android 获取设备区域设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23348954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android get device locale
提问by trante
Upon installation of my Android program I check for device locale:
安装我的 Android 程序后,我会检查设备区域设置:
String deviceLocale=Locale.getDefault().getLanguage();
If deviceLocale is inside my supported languages (english, french, german) I don't change locale.
如果 deviceLocale 在我支持的语言(英语、法语、德语)内,我不会更改语言环境。
But for instance say that if I don't support device's language: for example spanish.
I set current locale to English, because most of the people can understand English partly.
但是例如说如果我不支持设备的语言:例如西班牙语。
我将当前语言环境设置为英语,因为大多数人可以部分理解英语。
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
pContext.getResources().updateConfiguration(config, null);
But after that, in other methods, when I check device's locale like this:
但在那之后,在其他方法中,当我像这样检查设备的语言环境时:
String deviceLocale=Locale.getDefault().getLanguage();
I get result as "English". But device's locale is Spanish.
我得到的结果是“英语”。但设备的语言环境是西班牙语。
Does getLanguage() gives current app's locale ?
How can I get device's locale ?
getLanguage() 是否提供当前应用程序的语言环境?
如何获取设备的语言环境?
Edit: In app's first run, it is an option to save device locale. But if user changes device locale after I save, I can't know new locale of the device. I can only know the locale that I saved in app install.
编辑:在应用程序的第一次运行中,它是保存设备区域设置的选项。但是如果用户在我保存后更改设备区域设置,我将无法知道设备的新区域设置。我只能知道我在应用安装中保存的语言环境。
回答by Emanuel Moecklin
There's a much simpler and cleaner way to do this than using reflection or parsing some system property.
有一种比使用反射或解析某些系统属性更简单、更清晰的方法来做到这一点。
As you noticed once you set the default Locale in your app you don't have access to the system default Locale any more. The default Locale you set in your app is valid only during the life cycle of your app. Whatever you set in your Locale.setDefault(Locale) is gone once the process is terminated . When the app is restarted you will again be able to read the system default Locale.
正如您所注意到的,一旦您在应用程序中设置了默认语言环境,您将无法再访问系统默认语言环境。您在应用中设置的默认 Locale 仅在应用的生命周期内有效。一旦进程终止,您在 Locale.setDefault(Locale) 中设置的任何内容都将消失。当应用程序重新启动时,您将再次能够读取系统默认区域设置。
So all you need to do is retrieve the system default Locale when the app starts, remember it as long as the app runs and update it should the user decide to change the language in the Android settings. Because we need that piece of information only as long as the app runs, we can simply store it in a static variable, which is accessible from anywhere in your app.
因此,您需要做的就是在应用程序启动时检索系统默认区域设置,只要应用程序运行就记住它,并在用户决定更改 Android 设置中的语言时更新它。因为我们只在应用程序运行时才需要这条信息,所以我们可以简单地将它存储在一个静态变量中,该变量可以从应用程序的任何位置访问。
And here's how we do it:
这是我们如何做到的:
public class MyApplication extends Application {
public static String sDefSystemLanguage;
@Override
public void onCreate() {
super.onCreate();
sDefSystemLanguage = Locale.getDefault().getLanguage();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
sDefSystemLanguage = newConfig.locale.getLanguage();
}
}
Using an Application (don't forget to define it in your manifest) we get the default locale when the app starts (onCreate()) and we update it when the user changes the language in the Android settings (onConfigurationChanged(Configuration)). That's all there is. Whenever you need to know what the system default language was before you used your setDefault call, sDefSystemLanguage will give you the answer.
使用应用程序(不要忘记在清单中定义它),我们会在应用程序启动时获得默认区域设置 (onCreate()),并在用户更改 Android 设置中的语言时更新它 (onConfigurationChanged(Configuration))。这就是全部。每当您在使用 setDefault 调用之前需要知道系统默认语言是什么时,sDefSystemLanguage 都会给您答案。
There's one issue I spotted in your code. When you set the new Locale you do:
我在您的代码中发现了一个问题。当您设置新的区域设置时,您会执行以下操作:
Configuration config = new Configuration();
config.locale = locale;
pContext.getResources().updateConfiguration(config, null);
When you do that, you overwrite all Configuration information that you might want to keep. E.g. Configuration.fontScale reflects the Accessibility settings Large Text. By settings the language and losing all other Configuration your app would not reflect the Large Text settings any more, meaning text is smaller than it should be (if the user has enabled the large text setting). The correct way to do it is:
当您这样做时,您将覆盖您可能想要保留的所有配置信息。例如 Configuration.fontScale 反映了辅助功能设置大文本。通过设置语言并丢失所有其他配置,您的应用程序将不再反映大文本设置,这意味着文本比应有的要小(如果用户启用了大文本设置)。正确的做法是:
Resources res = pContext.getResources();
Configuration config = res.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLocale(Locale.CANADA);
}
else {
configuration.locale = Locale.CANADA;
}
res.updateConfiguration(config, null);
So instead of creating a new Configuration object we just update the current one.
因此,我们只是更新当前的对象,而不是创建一个新的 Configuration 对象。
回答by Aniket Awati
You can access global locale by -
您可以通过以下方式访问全局语言环境 -
defaultLocale = Resources.getSystem().getConfiguration().locale;
defaultLocale = Resources.getSystem().getConfiguration().locale;
Take a look at http://developer.android.com/reference/android/content/res/Resources.html#getSystem()-
看看http://developer.android.com/reference/android/content/res/Resources.html#getSystem()-
Returns a global shared Resources object that provides access to only system resources (no application resources)
返回一个全局共享资源对象,该对象仅提供对系统资源(无应用程序资源)的访问
Update: As pointed out in comments 'locale' field is deprecated and you need to use getLocales()instead.
更新:正如评论中指出的那样,'locale' 字段已被弃用,您需要改用getLocales()。
defaultLocale = Resources.getSystem().getConfiguration().getLocales().get(0);
defaultLocale = Resources.getSystem().getConfiguration().getLocales().get(0);
回答by greywolf82
The best way to design the app is to use a default lang, English in your case, under values/ and you can add addition langs under values-XX/. In this way when a language is not supported Android fallback to your default, so English. Let the OS does the work for you :) However, yes if you change the locale you'll get your last settings, so you have to save that information somewhere.
设计应用程序的最佳方法是在 values/ 下使用默认语言,在您的情况下为英语,您可以在 values-XX/ 下添加其他语言。这样当Android 不支持一种语言时回退到你的默认,所以英语。让操作系统为您完成工作:) 但是,是的,如果您更改区域设置,您将获得最后的设置,因此您必须将该信息保存在某处。
回答by Amit Gupta
As you are changing theApplication language programatically like
当你改变Application language programatically like
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
pContext.getResources().updateConfiguration(config, null);
And
和
But after that, in other methods, when I check device's locale like this:
String deviceLocale=Locale.getDefault().getLanguage();
I get result as "English". But device's locale is Spanish.
So instead of that use this below code to get thedevice's Local
因此,而不是使用下面的代码来获取device's Local
try {
Process exec = Runtime.getRuntime().exec(new String[]{"getprop", "persist.sys.language"});
String locale = new BufferedReader(new InputStreamReader(exec.getInputStream())).readLine();
exec.destroy();
Log.e("", "Device locale: "+locale);
} catch (IOException e) {
e.printStackTrace();
}
OUTPUT:Spanish
Check this
输出:Spanish
检查这个
Hope this exactly you are looking for.
希望这正是您正在寻找的。
回答by ozbek
Although, the answer by @user2944616is politically correct, that does not give an answer to the actual question posed.
尽管@user2944616的回答在上是正确的,但这并没有回答提出的实际问题。
So, if I really had to know the user set system locale, I'd use reflection (do not know any better option ATM):
所以,如果我真的必须知道用户设置的系统区域设置,我会使用反射(不知道有什么更好的选择 ATM):
private String getSystemPropertyValue(String name) {
try {
Class<?> systemProperties = Class.forName("android.os.SystemProperties");
try {
Method get = systemProperties.getMethod("get", String.class, String.class);
if (get == null) {
return "Failure!?";
}
try {
return (String)get.invoke(systemProperties, name, "");
} catch (IllegalAccessException e) {
return "IllegalAccessException";
} catch (IllegalArgumentException e) {
return "IllegalArgumentException";
} catch (InvocationTargetException e) {
return "InvocationTargetException";
}
} catch (NoSuchMethodException e) {
return "SystemProperties.get(String key, String def) method is not found";
}
} catch (ClassNotFoundException e) {
return "SystemProperties class is not found";
}
}
With that given and device locale set to Spanish (United States) / Espa?ol (Estados Unidos) following string
将给定的设备区域设置为西班牙语(美国)/ Espa?ol(Estados Unidos)以下字符串
<string name="system_locale">System locale: <xliff:g id="profile_name">%1$s</xliff:g>_<xliff:g id="device_name">%2$s</xliff:g></string>
and this code
和这段代码
private static final String SYS_COUNTRY = "persist.sys.country";
private static final String SYS_LANG = "persist.sys.language";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.locale);
tv.setText(getString(R.string.system_locale, getSystemPropertyValue(SYS_LANG),
getSystemPropertyValue(SYS_COUNTRY)));
}
yields following screen:
产生以下屏幕:
If desired, one could also easily construct Locale
instance using the above:
如果需要,还可以Locale
使用上述方法轻松构建实例:
Locale locale = new Locale(getSystemPropertyValue(SYS_LANG),
getSystemPropertyValue(SYS_COUNTRY));
Log.d(TAG, "Language: " + locale.getLanguage());
Log.d(TAG, "Country: " + locale.getCountry());
Log output:
日志输出:
D/GetSystemLocale(5697): Language: es
D/GetSystemLocale(5697): Country: US
Hope this helps.
希望这可以帮助。
回答by k0sh
you should use String deviceLocale= Locale.getDefault().getDisplayLanguage();
to display the language instead of
您应该使用String deviceLocale= Locale.getDefault().getDisplayLanguage();
来显示语言而不是
String deviceLocale=Locale.getDefault().getLanguage();
check out this answer it may help you if above does not. Clickable
看看这个答案,如果上面没有,它可能会帮助你。可点击
回答by Hasham Tahir
To get the device locale use this
要获取设备区域设置,请使用此
Locale current = context.getResources().getConfiguration().locale;
and current.toString()
will return you "en" "ar" etc
并且current.toString()
将返回“EN”“AR”等