How does Hilt work internally in Android SDK?

Hilt is a dependency injection library designed to simplify Dagger's usage in Android applications. It integrates with the Android framework to automatically generate the necessary code for setting up the dependency graph. Hilt reduces the boilerplate code involved in Dagger setup by providing predefined components and scopes that are specific to Android lifecycle management.

The core concepts of Hilt include:

  • Modules: These are classes that define how to provide dependencies. In Hilt, you annotate your module classes with @Module and @InstallIn to specify where the dependencies will be available.
  • Components: Hilt has predefined components (like SingletonComponent, ActivityComponent, FragmentComponent) that correspond to various lifecycles, helping manage the lifespan of dependencies.
  • Injecting Dependencies: With Hilt, you can use @Inject to request dependencies in fields, constructors, or methods, managing the configuration automatically during the lifecycle of Android components.

Here’s a simple example that demonstrates how Hilt is set up in an Android application:


    @HiltAndroidApp
    class MyApplication : Application() {
    }
    
    @InstallIn(ActivityComponent::class)
    @Module
    object NetworkModule {
        @Provides
        fun provideRetrofit(): Retrofit {
            return Retrofit.Builder()
                .baseUrl("https://api.example.com")
                .build()
        }
    }

    @AndroidEntryPoint
    class MainActivity : AppCompatActivity() {
        @Inject lateinit var retrofit: Retrofit
        
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            // Now you can use 'retrofit' to make network requests.
        }
    }
    

android hilt dependency injection hilt internal workings hilt android sdk hilt guide hilt examples