Android Kotlin:Hilt 如何获取 Application class 的对象?

Android Kotlin: Hilt how to get object of Application class?

我在这里创建了应用程序 class 依赖项。现在我想访问

@Module
@InstallIn(SingletonComponent::class)
class MyApplicationModule {
    @Provides
    fun providesMainApplicationInstance(application: MainApplication): MainApplication =
        application
}

我的申请class是:

@HiltAndroidApp
class MainApplication : Application() {
    override fun onCreate() {
        super.onCreate()
    }

    fun printData(){
        Log.d("Test","Awesome print data")
    }


}

我想从 activity. 调用 printData() 函数 我已经使用字段注入访问应用程序 class 但它给出了错误.. .

@Inject lateinit var mainApplication: MainApplication

错误

[Dagger/DependencyCycle] Found a dependency cycle:
 MainApplication is injected at MyApplicationModule.providesMainApplicationInstance(application)

这应该有效:

@Module
@InstallIn(SingletonComponent::class)
class MyApplicationModule {

    @Provides
    fun providesMainApplicationInstance(@ApplicationContext context: Context): MainApplication {
        return context as MainApplication
    }
}

Hilt 可以注入应用上下文。你需要简单地施放它。

如果好用请告诉我。