在attachBaseContext中使用注入匕首的对象 [英] Using dagger-injected objects in attachBaseContext

查看:70
本文介绍了在attachBaseContext中使用注入匕首的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在活动的 attachBaseContext 中访问我的 SharedPreferences 实例(以便在此处设置语言环境),但是需要注入 SharedPreferences 实例不可用,因为注入是在 attachBaseContext 调用之后运行的 onCreate 方法中进行的.我正在使用dagger2进行依赖注入.

I need to access my SharedPreferences instance in the attachBaseContext of my activity (so I can set the locale there), but the injected SharedPreferences instance is not available there as the injection is happening in the onCreate method, which is running after the attachBaseContext call. I am using dagger2 for dependency injection.

有什么想法可以避免创建新的 SharedPreferences 实例吗?

Any idea how I can avoid creating a new SharedPreferences instance?

好吧,所以我认为问题是我试图过多使用匕首,我认为在这种情况下,它根本不合适.在每个活动的 attachBaseContext 中,我必须更新语言环境,并将此更新逻辑提取到 LocaleManager 中,该逻辑需要访问 SharedPreferences 实例.以及我在 attachBaseContext 中获得的 Context . SharedPreferences 实例已经在 AppModule 中,但是我仍然不能 @Inject 将该实例添加到 attachBaseContext 之前的活动中.调用,因为活动的注入发生在 attachBaseContext 之后.

Ok, so I think the problem is that I am trying to use dagger too much, I think in this case it is simply not suitable. In the attachBaseContext of each activity I have to update the locale, and I extracted this updating logic to a LocaleManager which needs access to the SharedPreferences instance and the Context that I get in attachBaseContext. The SharedPreferences instance is already in the AppModule, but I still cannot @Inject it to the activities before the attachBaseContext call, as the activity`s injections happen after attachBaseContext.

推荐答案

只要您可以访问 Component ,就可以添加

As long as you can access your Component you could add a provision method

@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {

    fun inject(myActivity: MyActivity)

    fun sharedPreferences(): SharedPreferences

    ...
}

,然后直接通过 Component 来访问您的 SharedPreferences :

and then access your SharedPreferences directly via the Component:

class MyActivity : AppCompatActivity() {

    override fun attachBaseContext(newBase: Context) {
        val sharedPreferences = component.sharedPreferences()
        ...
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        component.inject(this)
    }

}

这篇关于在attachBaseContext中使用注入匕首的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆