简体   繁体   中英

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

Here i created application class dependency. now i want to access

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

My application class is:

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

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


}

i want to call printData() function from the activity. i have used field injection to access application class but it gives error...

@Inject lateinit var mainApplication: MainApplication

ERROR

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

This should work:

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

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

Hilt can inject application context. You need to simply cast it.

Let me know if it's good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM