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

How to get Component already initialized with Application context

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

我知道有像 or this 这样的类似问题,但这使用了 AndroidInjector,我变得更加迷茫。我想了解的是,一旦 ContextComponent 被初始化并且是 Singleton,我如何检索 ContextComponent 的实例(包含应用程序的上下文)以便调用 ContextComponent.getSharedPreferenceSpecific() 并获取 SharedPreferenceManagerSpecific 的实例使用应用程序的上下文初始化?

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

执行activity的代码时出现的错误i:

java.lang.RuntimeException: 无法启动 activity 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(){
    ...
    }

}

Dagger 不会在任何地方存储组件实例。甚至 @Singleton 组件也不行:就 Dagger 而言,@Singleton 只是另一个范围。为了在您的 Application class 中创建一个组件并在您的 Activity class 中使用它,您需要自己将其存储在某个地方。

在大多数 Android 使用 Dagger 的应用程序中,组件存储在 Application:

class MyApplication : Application() {
    
    // You could set a lateinit var in onCreate instead
    // if you don't use any ContentProviders.
    val component by lazy {
        DaggerContextComponent.builder().contextModule(ContextModule(this)).build()
    }
    
}

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val component = (application as MyApplication).component
        val sharedPreference = component.getSharedPreferenceSpecific()
    }

}