通过自定义应用程序更改Android系统语言

问题描述 投票:0回答:1

是否可以通过自定义应用程序更改 Android 设备语言?谢谢您提前的答复。

我正在创建Android应用程序。该应用程序应更改系统语言。我想知道这可能吗

android system
1个回答
0
投票

我还必须将其实现到我的应用程序中。

经过大量挖掘,我发现了这个方法来设置 userSetLocale。

要使用它,您需要声明 WRITE_SETTINGS 权限

    <uses-permission android:name="android.permission.WRITE_SETTINGS"
    tools:ignore="ProtectedPermissions" />

您可能还需要 CHANGE_CONFIGURATION 权限

<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"
    tools:ignore="ProtectedPermissions" />

要授予 WRITE_SETTINGS 您可以手动授予应用程序权限或通过 ADB 授予 appop

appops set PACKAGE_NAME android:write_settings allow

对于 CHANGE_CONFIGURATION 您也可以通过 ADB 授予它

pm grant PACKAGE_NAME android.permission.CHANGE_CONFIGURATION

现在您可以使用此方法来设置系统区域设置

public static void setSystemLocale(ArrayList<Locale> languageList) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
    //Tested on Android 12
    Class<?> clazz = Class.forName("android.app.ActivityManager");

    Method getServiceMethod = clazz.getMethod("getService", new Class[0]);
    getServiceMethod.setAccessible(true);
    Object service = getServiceMethod.invoke(clazz, new Object[0]);

    Method getConfigurationMethod = Class.forName("android.app.IActivityManager").getMethod("getConfiguration", new Class[0]);
    getConfigurationMethod.setAccessible(true);
    Configuration configuration = (Configuration) getConfigurationMethod.invoke(service, new Object[0]);

    configuration.getClass().getField("userSetLocale").setBoolean(configuration, true);
    configuration.setLocales(new LocaleList(languageList.toArray(new Locale[languageList.size()])));

    Method updateConfigurationMethod = Class.forName("android.app.IActivityManager").getMethod("updatePersistentConfiguration", new Class[]{Configuration.class});
    updateConfigurationMethod.setAccessible(true);
    updateConfigurationMethod.invoke(service, new Object[]{configuration});
}

您可能必须使用不同的方法来更新配置。 对于我的设备 (Android 12) updatePersistentConfiguration 有效。对于旧版 Android,它是 updateConfiguration。

这里是IActivityManager的源代码

© www.soinside.com 2019 - 2024. All rights reserved.