Skip to content

Instantly share code, notes, and snippets.

@AfzalivE
Last active April 7, 2019 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AfzalivE/d8d1ea11248bbf23fc9c52c7aec9b371 to your computer and use it in GitHub Desktop.
Save AfzalivE/d8d1ea11248bbf23fc9c52c7aec9b371 to your computer and use it in GitHub Desktop.
Class to change android OS locale (works till API 24, M)
public class LocaleChanger {
public static void setLocale(ArrayList<Locale> arrayList) {
try {
Class cls = Class.forName("android.app.ActivityManagerNative");
Method method = cls.getMethod("getDefault", new Class[0]);
method.setAccessible(true);
Object invoke = method.invoke(cls, new Object[0]);
method = cls.getMethod("getConfiguration", new Class[0]);
method.setAccessible(true);
Configuration configuration = (Configuration) method.invoke(invoke, new Object[0]);
persistLocaleChanges(configuration);
if (Build.VERSION.SDK_INT >= 24) {
configuration = setLocale24(configuration, arrayList);
} else {
configuration.locale = arrayList.get(0);
}
Method method2 = cls.getMethod("updateConfiguration", new Class[]{Configuration.class});
method2.setAccessible(true);
method2.invoke(invoke, new Object[]{configuration});
} catch (Exception e) {
e.printStackTrace();
Timber.e(e.getMessage() == null ? e.getCause().getMessage() : e.getMessage());
}
}
private static void persistLocaleChanges(Configuration configuration) {
try {
configuration.getClass().getField("userSetLocale").setBoolean(configuration, true);
} catch (IllegalAccessException e) {
Timber.d(e, "Can't persist locale settings");
} catch (NoSuchFieldException e) {
Timber.d(e, "Can't persist locale settings");
}
}
@TargetApi(24)
private static Configuration setLocale24(Configuration configuration, ArrayList<Locale> arrayList) {
configuration.setLocales(new LocaleList((Locale[]) arrayList.toArray(new Locale[arrayList.size()])));
return configuration;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment