I am trying to change the locale of an app so that it is the user's choice through the following code
public static void updateLanguage(Context ctx) {
SharedPreferencesManager sharedPreferencesManager = new SharedPreferencesManager(ctx);
String lang = sharedPreferencesManager.readPreference(Constants.SHARED_PREFERENCES_LOCALE, "");
if (StringUtils.isEmptyOrNull(lang)) {
lang = Locale.getDefault().getLanguage();
}
setLanguage(ctx, lang);
}
@SuppressWarnings("deprecation")
public Locale getSystemLocaleLegacy(Configuration config) {
return config.locale;
}
@TargetApi(Build.VERSION_CODES.N)
public Locale getSystemLocale(Configuration config) {
return config.getLocales().get(0);
}
@SuppressWarnings("deprecation")
public static void setSystemLocaleLegacy(Configuration config, Locale locale) {
config.locale = locale;
}
@TargetApi(Build.VERSION_CODES.N)
public static void setSystemLocale(Configuration config, Locale locale) {
config.setLocale(locale);
}
public static void setLanguage(Context context, String languageCode) {
Locale locale = new Locale(languageCode);
Locale.setDefault(locale);
Configuration config = new Configuration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
setSystemLocale(config, locale);
} else {
setSystemLocaleLegacy(config, locale);
}
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
}
Where I run the updateLanguage (this) method in the Application class.
I have several devices in which some works perfectly but in others the Locale.getDefault (). getLanguage () is set after few executions, although the sharedPreferences continues to define another. p>
For example, I have the device in Spanish and set the I want the app in English (in the configuration menu where I save the value in sharePreferences). Nothing else finished to set it, it works correctly, the application is displayed in English. But after some executions, the application is set in Spanish although the value of sharedPreferences remains in English.
Could someone tell me if I do something wrong or why some devices work correctly and others do not? (It also happens that in several devices of the same model reacts differently)