【发布时间】:2020-09-22 19:05:32
【问题描述】:
我刚开始使用 dagger2,尽管自己阅读并记录了自己的主要思想,但我不明白哪种方法是注入应用程序上下文的正确方法。
我知道有类似的问题,如 this 或 this 但这使用了 AndroidInjector,我更加迷失了。我想了解的是,一旦 ContextComponent 已被初始化并且是单例,我如何检索 ContextComponent 的实例(包含应用程序的上下文)以调用 ContextComponent.getSharedPreferenceSpecific() 并获取 SharedPreferenceManagerSpecific 初始化的实例应用程序的上下文?
这些是我创建的类,SharedPreferenceManagerSpecific 只是为了了解如何将上下文注入到一个类中。
我在执行activity代码时遇到的错误i:
java.lang.RuntimeException: 无法启动活动 ComponentInfo{com.amgdeveloper.articleReader/com.amgdeveloper.articleReader.ui.MainActivity}: java.lang.IllegalStateException: com.amgdeveloper.articleReader.dagger.ContextModule 必须设置 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
ContextModule.kt
@Module
class ContextModule(private val app: Application) {
@Provides
@Singleton
fun provideContext(): Context = app
}
ContextComponent.tk
@Singleton
@Component(modules = [ContextModule::class])
interface ContextComponent {
fun getSharedPreferenceSpecific ():SharedPreferenceManagerSpecific
fun inject (application: MyApplication)
fun inject (application: MainActivity)
MyApplication.kt
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
DaggerContextComponent.builder().contextModule(ContextModule(this)).build()
}
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val component = DaggerContextComponent.builder().build()
val sharedPreference = component.getSharedPreferenceSpecific()
}
}
SharedPreferenceManagerSpecific.kt
public class SharedPreferenceManagerSpecific () {
lateinit var myContext : Context
@Inject constructor( context: Context) : this() {
myContext=context
}
fun saveIntoSharedPreferences(){
...
}
}
【问题讨论】:
标签: java android dependency-injection dagger-2 dagger