How to integrate Hilt with other Android components?

Integrating Hilt with Other Android Components

Hilt is a dependency injection library built on top of Dagger that simplifies the use of dependency injection in Android applications. Below are examples of how to integrate Hilt with various Android components.

1. Hilt with Activities

To use Hilt in an Activity, you simply annotate the Activity with @AndroidEntryPoint. This will allow the Activity to request dependencies from the Hilt container.

@AndroidEntryPoint class MainActivity : AppCompatActivity() { @Inject lateinit var repository: MyRepository override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Now you can use the repository } }

2. Hilt with Fragments

Similarly, for Fragments, you also apply the @AndroidEntryPoint annotation.

@AndroidEntryPoint class MyFragment : Fragment() { @Inject lateinit var viewModelFactory: ViewModelFactory override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Use your ViewModel factory } }

3. Hilt with ViewModels

To use Hilt with ViewModels, the ViewModel should use @HiltViewModel annotation. It allows Hilt to provide dependencies directly to the ViewModel.

@HiltViewModel class MyViewModel @Inject constructor( private val repository: MyRepository ) : ViewModel() { // Your ViewModel code }

4. Hilt with Services

To inject dependencies into a Service, apply the @AndroidEntryPoint annotation to the service class like this:

@AndroidEntryPoint class MyService : Service() { @Inject lateinit var repository: MyRepository override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { // Use your repository return START_STICKY } }

Keywords: Hilt Dependency Injection Android Components Activities Fragments ViewModels Services