Hilt Application

Note: Examples on this page assume usage of the Gradle plugin. If you are not using the plugin, please read this page for details.

Hilt Application

All apps using Hilt must contain an Application class annotated with @HiltAndroidApp. @HiltAndroidApp kicks off the code generation of the Hilt components and also generates a base class for your application that uses those generated components. Because the code generation needs access to all of your modules, the target that compiles your Application class also needs to have all of your Dagger modules in its transitive dependencies.

Just like other Hilt Android entry points, Applications are members injected as well. This means you can use injected fields in the Application after super.onCreate() has been called.

Note: Since all injected fields are created at the same time in onCreate, if an object is only needed later or conditionally, remember that you can use a Provider to defer injection. Especially in the Application class which is on the critical startup path, avoiding unnecessary injections can be important to performance.

For example, take the class called MyApplication that extends MyBaseApplication and has a member variable Bar:

Java
Kotlin
public final class MyApplication extends MyBaseApplication {
  @Inject Bar bar;

  @Override public void onCreate() {
    super.onCreate();

    MyComponent myComponent =
        DaggerMyComponent
            .builder()
            ...
            .build();

    myComponent.inject(this);
  }
}
class MyApplication : MyBaseApplication() {
  @Inject lateinit var bar: Bar

  override fun onCreate() {
    super.onCreate()

    val myComponent =
        DaggerMyComponent
            .builder()
            ...
            .build()

    myComponent.inject(this)
  }
}

With Hilt’s members injection, the above code becomes:

Java
Kotlin
@HiltAndroidApp
public final class MyApplication extends MyBaseApplication {
  @Inject Bar bar;

  @Override public void onCreate() {
    super.onCreate(); // Injection happens in super.onCreate()
    // Use bar
  }
}
@HiltAndroidApp
class MyApplication : MyBaseApplication() {
  @Inject lateinit var bar: Bar

  override fun onCreate() {
    super.onCreate() // Injection happens in super.onCreate()
    // Use bar
  }
}