Using dagger-injected objects in attachBaseContext

自古美人都是妖i 提交于 2021-02-08 13:10:30

问题


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.

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

EDIT:

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.


回答1:


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

    ...
}

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)
    }

}


来源:https://stackoverflow.com/questions/50716906/using-dagger-injected-objects-in-attachbasecontext

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!