如何获取已使用应用程序上下文初始化的组件

问题描述

我刚刚开始使用dagger2,尽管已经阅读并记录了自己的主要思想,但我不知道哪种方法是注入应用程序上下文的正确方法。

我知道也有类似的问题,例如thisthis,但这使用的是AndroidInjector,我迷路了。我想了解的是,一旦ContextComponent已初始化并且是Singleton,我如何才能检索ContextComponent的实例(包含应用程序的上下文)以便调用ContextComponent.getSharedPreferenceSpecific()并获取使用以下方法初始化的SharedPreferenceManagerSpecific的实例应用程序的上下文?

这些是我创建的类,SharedPreferenceManagerSpecific只是为了了解如何向类注入上下文。

我在执行活动代码时遇到的错误:

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(){
    ...
    }

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)