How to use Hilt in an Android app?

Hilt is a dependency injection library for Android that simplifies the process of using Dagger for dependency injection in Android apps. Below you'll find a brief guide on how to use Hilt in your Android application with a practical example.

Getting Started with Hilt

  1. Add Hilt dependencies to your project:
  2. dependencies {
                implementation "com.google.dagger:hilt-android:"
                kapt "com.google.dagger:hilt-compiler:"
            }
  3. Apply the Hilt Gradle plugin in your build.gradle file:
  4. plugins {
                id 'dagger.hilt.android.plugin'
            }
  5. Annotate your application class with @HiltAndroidApp:
  6. @HiltAndroidApp
            class MyApplication : Application() {
            }
  7. Create a module to provide dependencies:
  8. @Module
            @InstallIn(SingletonComponent::class)
            object NetworkModule {
                @Provides
                @Singleton
                fun provideApiService(): ApiService {
                    return Retrofit.Builder()
                        .baseUrl("https://api.example.com")
                        .build()
                        .create(ApiService::class.java)
                }
            }
  9. Inject the dependencies in your activity or fragment:
  10. @AndroidEntryPoint
            class MainActivity : AppCompatActivity() {
                @Inject lateinit var apiService: ApiService
                
                override fun onCreate(savedInstanceState: Bundle?) {
                    super.onCreate(savedInstanceState)
                    setContentView(R.layout.activity_main)
                    // Use apiService here
                }
            }

Hilt Android Dependency Injection Dagger Hilt Tutorial Android Development