问题
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