【问题标题】:Not able to use dagger-injected objects in attachBaseContext() to update locale无法在 attachBaseContext() 中使用 dagger-injected 对象来更新语言环境
【发布时间】:2018-11-13 09:23:29
【问题描述】:
我正在使用 dagger,我必须更新 activity 的 attachBaseContext 中的语言环境,我将语言环境更新逻辑保留在 LocaleManager 中,当我尝试在里面使用这个 LocaleManager 实例时,LocaleManager 实例已经在 appModule 中attachBaseContext 我得到空指针异常
因为活动的注入发生在attachBaseContext 内部onCreate() 之后。
【问题讨论】:
标签:
android
android-7.0-nougat
dagger
【解决方案1】:
正如你所说,这种情况正在发生,因为注入是在调用 attachBaseContext 之后发生的。
我实际上不确定这里的问题是什么,但我遇到了同样的问题,但不幸的是我无法用匕首解决它。我需要在attachBaseContext 中创建一个新的LocaleManager,如下所示:
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(new LocaleManager(base).updateContext());
}
其中updateContext 返回具有更新语言环境的上下文,如下所示:
public Context updateContext() {
Locale locale = new Locale(DESIRED_LANGUAGECODE);
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResourcesLocale(locale);
}
return updateResourcesLocaleLegacy(locale);
}
@SuppressWarnings("deprecation")
private Context updateResourcesLocaleLegacy(Locale locale) {
Resources resources = mContext.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return mContext;
}
@TargetApi(Build.VERSION_CODES.N)
private Context updateResourcesLocale(Locale locale) {
Configuration configuration = mContext.getResources().getConfiguration();
configuration.setLocale(locale);
return mContext.createConfigurationContext(configuration);
}
【解决方案2】:
解决方案是将您的对象注入到 Application 类中,以便在应用程序启动后立即可用。
在您的应用程序类(扩展应用程序的类)中
/**
* Request UserLanguageProvider here so it's initialized as soon as possible and can be used by
* [LocaleStaticInjector]
*/
@Inject
lateinit var userLanguageProvider: UserLanguageProvider
在 BaseActivity.kt 中
override fun attachBaseContext(newBase: Context) {
val context: Context = LanguageContextWrapper.wrap(newBase, LocaleStaticInjector.userLanguageProvider)
super.attachBaseContext(context)
}
在我的自定义类中:
/**
* We use a static object to inject the locale helper dependency because it's used in
* [BaseActivity#attachBaseContext] which is called before the activity is injected!!
*/
object LocaleStaticInjector {
lateinit var userLanguageProvider: UserLanguageProvider
}