Android dagger hilt injecting application context in a Povides function

Hilt provides some predefined qualifiers. For example, as you might need the Context class from either the application or the activity, Hilt provides the @ApplicationContext and @ActivityContext qualifiers.

Suppose that the AnalyticsAdapter class from the example needs the context of the activity. The following code demonstrates how to provide the activity context to AnalyticsAdapter

class AnalyticsAdapter @Inject constructor(
    @ActivityContext private val context: Context,
    private val service: AnalyticsService
) { ... }

Provide the application context to in a Provide function

@InstallIn(ViewModelComponent::class)
@Module
object TaskModule {
    @Provides
    fun provideTasksLocalDataSource(@ApplicationContext context: Context): TasksDataSource {
        val database = createDataBase(context)
        return TasksLocalDataSource(database.taskDao())
    }
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search