Android设置语言
应用语言的切换
单纯的切换自身应用的语言。
Resources resources = getResources(); DisplayMetrics dm = resources.getDisplayMetrics(); Configuration config = resources.getConfiguration(); config.setLocale(locale); resources.updateConfiguration(config, dm);
系统语言的切换
切换整个系统的语言。
在6.0的系统中,切换系统语言的方法位于LocalePicker.java文件中(7.0后有变化):
#android/frameworks/base/core/java/com/android/internal/app/LocalePicker.java public static void updateLocale(Locale locale) { try { IActivityManager am = ActivityManagerNative.getDefault(); Configuration config = am.getConfiguration(); config.setLocale(locale); config.userSetLocale = true; am.updateConfiguration(config); // Trigger the dirty bit for the Settings Provider. BackupManager.dataChanged("com.android.providers.settings"); } catch (RemoteException e) { // Intentionally left blank } }
我们可以通过下面两种方法来修改系统语言:
1. 修改persist.sys.locale的值
adb shell命令:通过 getprop 和 setprop persist.sys.locale
的值来实现语言的切换,但是这种方法需要重启后才能生效。例如:setprop persist.sys.locale zh-CN
2. 程序中通过反射来修改
try { Class iActivityManager = Class.forName("android.app.IActivityManager"); Class activityManagerNative = Class.forName("android.app.ActivityManagerNative"); Method getDefault = activityManagerNative.getDeclaredMethod("getDefault"); Object objIActMag = getDefault.invoke(activityManagerNative); Method getConfiguration = iActivityManager.getDeclaredMethod("getConfiguration"); Configuration config = (Configuration) getConfiguration.invoke(objIActMag); config.locale = locale; Class clzConfig = Class.forName("android.content.res.Configuration"); java.lang.reflect.Field userSetLocale = clzConfig.getField("userSetLocale"); userSetLocale.set(config, true); Class[] clzParams = {Configuration.class}; Method updateConfiguration = iActivityManager.getDeclaredMethod("updateConfiguration", clzParams); updateConfiguration.invoke(objIActMag, config); BackupManager.dataChanged("com.android.providers.settings"); } catch (Exception e) { e.printStackTrace(); }
Author:xcz1899 Link: https://www.jianshu.com/p/53b4df276b01 Source: Jane's Book Copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.