更改应用程序区域设置后如何获取设备区域设置

时间:2013-01-18 08:06:36

标签: android location locale device

我正在根据用户选择更改应用程序区域设置。独立于设备区域设置。

使用

public void setDefaultLocale(Context context, String locale) {
        Locale appLoc = new Locale(locale);
        Locale.setDefault(appLoc);
        Configuration appConfig = new Configuration();
        appConfig.locale = appLoc;
        context.getResources().updateConfiguration(appConfig,
                context.getResources().getDisplayMetrics());
    }

但我想知道设备区域设置也是什么。

当我试图得到这个时,我总是得到我设置为应用程序的语言环境。

例如:应用程序位于 ENGLISH ,设备位于 中文 。 我总是得到 英语

用于获取语言环境,

选项1。

String locale = context.getResources().getConfiguration().locale.getCountry();

选项2。

String local_country = ((Activity) context).getBaseContext().getResources().getConfiguration().locale.getCountry();

任何帮助都将受到高度赞赏!!!

4 个答案:

答案 0 :(得分:7)

我问过类似的东西并找到了答案,对不起,如果已经晚了:

要查找系统区域设置,请使用:

defaultLocale = Resources.getSystem().getConfiguration().locale;

无论为app / activity设置了哪个默认语言环境,它都会获得系统区域设置。

答案 1 :(得分:6)

我绝对不确定这对不同设备的可移植性如何:

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();
}

如果你想要国家部分:persist.sys.country

答案 2 :(得分:1)

如果您需要在Android 7.0以下支持-Nougat(API级别24),则可以使用以下代码:

@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
// ToDo: Adjust this method once the target API is 24 or higher!
private Locale getLocale()
{
  if(Build.VERSION.SDK_INT >= 24)
  {
    return Resources.getSystem().getConfiguration().getLocales().get(0);
  }

  else
  {
    return Resources.getSystem().getConfiguration().locale;
  }
}

请注意有关deprecationNewApi的注释。以API 24或更高版本为目标后,请调整此方法。受this答案的启发。

答案 3 :(得分:0)

对于那些使用Daniel Fekete的解决方案的人来说:

Process exec = Runtime.getRuntime().exec(new String[]{"getprop", "persist.sys.language"});
String locale = new BufferedReader(new InputStreamReader(exec.getInputStream())).readLine();
exec.destroy();

请注意最新Android Api(+21)上的区域设置可能 EMPTY !而不是使用persist.sys.language使用 persist.sys.locale

exec = Runtime.getRuntime().exec(new String[]{"getprop", "persist.sys.locale"});
locale = new BufferedReader(new InputStreamReader(exec.getInputStream())).readLine();
exec.destroy();
相关问题