How to get the device locale after changing the application locale

牧云@^-^@ 提交于 2019-11-29 18:46:55

问题


I am changing the application locale based on user choice. Independent of device locale.

using

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

But I want to know what will be the device locale also.

When I am trying to get this I always getting the locale which I have set to application.

ex: applictaion is in ENGLISH and device is in CHINESE. I am always getting english.

for getting locale using,

option 1.

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

option 2.

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

Any help will be highly appreciated!!!


回答1:


I am absolutely unsure how portable this is to different devices:

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

And if you want the country part: persist.sys.country




回答2:


I asked something similar and found this answer, sorry if it is late:

To find the system locale use:

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

It gets the system locale, no matter which default locale is set for the app/activity.




回答3:


for those whom are using Daniel Fekete 's solution which is :

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

Be aware of that locale might be EMPTY on latest Android Api(+21)! instead of using persist.sys.language use persist.sys.locale

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


来源:https://stackoverflow.com/questions/14394735/how-to-get-the-device-locale-after-changing-the-application-locale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!