问题描述
我正在处理一个问题,但我不明白为什么会这样。我有一个带有服务的应用程序,可以获取用户的位置。当我打开应用程序并更改语言时,它可以工作,但是在运行此服务时,语言始终为英语。 我在每项活动和服务中都有此方法。
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(LocaleHelper.onAttach(newBase));
Log.d(TAG,"Language changed to " + Hawk.get(Constants.disPLAY_LANGUAGE_KEY));
}
当我在服务中评论此方法时,一切正常,但是该服务从不更改其默认语言(英语)。 LocaleHelper来自另一个堆栈溢出问题。
public static Context onAttach(Context context) {
String locale = getPersistedLocale();
return setLocale(context,locale);
}
public static String getPersistedLocale() {
return Hawk.get(Constants.disPLAY_LANGUAGE_KEY,"bg");
}
public static Context setLocale(Context context,String localeSpec) {
Locale locale;
if (localeSpec.equals("system")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
locale = Resources.getSystem().getConfiguration().getLocales().get(0);
} else {
locale = Resources.getSystem().getConfiguration().locale;
}
} else {
locale = new Locale(localeSpec);
}
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context,locale);
} else {
return updateResourcesLegacy(context,locale);
}
}
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context,Locale locale) {
Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
configuration.setLayoutDirection(locale);
return context.createConfigurationContext(configuration);
}
private static Context updateResourcesLegacy(Context context,Locale locale) {
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
configuration.setLayoutDirection(locale);
resources.updateConfiguration(configuration,resources.getdisplayMetrics());
return context;
}
我不知道为什么更改服务基础上下文会更改我的其他活动显示语言。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)