In Hilt, what do @HiltAndroidApp and @AndroidEntryPoint do, and what fails when an injected fragment's host activity lacks @AndroidEntryPoint?
answer
- generated Hilt_ base classes
- Application holds the root component
- fields filled in super.onCreate()
- components nest: activity, then fragment
- runtime check on the fragment's host
basics
~20 s@HiltAndroidApp on the Application triggers Hilt's code generation and holds the app-wide SingletonComponent; @AndroidEntryPoint makes an activity, fragment, view, service or receiver injectable. A Hilt fragment inside a non-Hilt activity throws IllegalStateException when it is attached.
solid answer
~40 s`@HiltAndroidApp` goes on the `Application` class. It triggers generation of the Hilt components and a `Hilt_NewsApplication` base class that creates the root `SingletonComponent` and injects the application's own fields in `super.onCreate()`; the Hilt Gradle plugin swaps in that base class for you. `@AndroidEntryPoint` does the same job for an activity, fragment, view, service or broadcast receiver: the generated base class attaches it to the right component at the right lifecycle point and fills its non-private `@Inject` fields, in `super.onCreate()` for an activity. Components nest, so a fragment's component is built from its activity's: a Hilt fragment hosted by an activity without `@AndroidEntryPoint` fails at runtime with "Hilt Fragments must be attached to an @AndroidEntryPoint Activity". The same check one level up catches an application class missing from the manifest's `android:name`.
code
kotlin · 26 lines@HiltAndroidApp
class NewsApplication : Application()
class ReadingAnalytics @Inject constructor() {
fun screenOpened(name: String) {
Log.d("ReadingAnalytics", "opened $name")
}
}
class ThumbnailLoader @Inject constructor()
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject lateinit var analytics: ReadingAnalytics
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) // injection happens here
analytics.screenOpened("home")
}
}
// Its host activity must also be @AndroidEntryPoint
@AndroidEntryPoint
class ArticleListFragment : Fragment() {
@Inject lateinit var thumbnails: ThumbnailLoader
}go deeper
Recall which annotation goes on the Application and which on activities and fragments, and that injected fields are usable after super.onCreate().
Explain the generated Hilt_ base classes, what the Gradle plugin rewrites, and why a fragment's component must be built from a Hilt activity's component.
Diagnose the two attach-time IllegalStateExceptions from their messages, and explain why the host rule can only be checked at runtime.
Frame entry points as the boundary where framework-created objects join the graph, and decide which framework classes a codebase should let inject fields at all.
## What the two annotations generate Hilt is the Android layer over Dagger: you never write or instantiate a component yourself. Instead you mark the Android classes that should receive dependencies, and Hilt generates the plumbing. - **`@HiltAndroidApp`** goes on exactly one class, your `Application` subclass. It is the signal to generate **all** of the app's Hilt components, because, as its own documentation puts it, all components are built in the same compilation as the annotated application. Every Hilt module and entry point therefore has to be a transitive compile dependency of the Gradle module that holds this class. - It also generates a base class named `Hilt_<YourApplication>`. That base class creates the root **`SingletonComponent`** and injects the application's own `@Inject` fields inside `super.onCreate()`. - **`@AndroidEntryPoint`** marks an activity, fragment, view, service or broadcast receiver. It generates a `Hilt_<ClassName>` base class that obtains the matching component at the right point in the lifecycle and injects the class's `@Inject` fields. - With the **Hilt Gradle plugin**, you keep writing `class MainActivity : AppCompatActivity()`; the plugin rewrites the superclass to the generated one. Without the plugin you pass the original base class to the annotation and extend `Hilt_MainActivity` by hand. ## Which classes can be entry points | Android class | Annotation | Component used to inject it | Fields ready | |---|---|---|---| | `Application` | `@HiltAndroidApp` | `SingletonComponent` | in `super.onCreate()` | | Activity (a `ComponentActivity`) | `@AndroidEntryPoint` | `ActivityComponent` | in `super.onCreate()` | | AndroidX `Fragment` | `@AndroidEntryPoint` | `FragmentComponent` | component created in `onAttach()` | | `View` | `@AndroidEntryPoint` | `ViewComponent` (or `ViewWithFragmentComponent`) | component created in the view's constructor | | `Service` | `@AndroidEntryPoint` | `ServiceComponent` | in `super.onCreate()` | | `BroadcastReceiver` | `@AndroidEntryPoint` | no component of its own: injected from `SingletonComponent` | in `onReceive()` | Hilt supports only activities that extend `ComponentActivity`, such as `AppCompatActivity`, and only AndroidX fragments. In a Compose app you do not annotate composables at all: you annotate the root activity, and screens obtain their ViewModels through Hilt's ViewModel support. Plain classes need none of this. A repository with an `@Inject constructor` is simply a binding Hilt knows how to build; only the classes the Android framework instantiates need an entry-point annotation, because Hilt cannot call their constructors. ## The host rule: components nest Hilt's components form a hierarchy: `SingletonComponent` is the root, `ActivityRetainedComponent` and `ActivityComponent` sit below it, and `FragmentComponent` is a child of `ActivityComponent`. A fragment's component is therefore created **from its host activity's component**, which is what lets a fragment inject activity-level bindings. The consequence is a runtime rule. When a Hilt fragment is attached, the generated code checks that the host is a Hilt activity, and if it is not, it throws `IllegalStateException` with the message "Hilt Fragments must be attached to an @AndroidEntryPoint Activity. Found: ...". The compiler cannot catch this, because which activity hosts which fragment is only known at runtime. The same pattern repeats one level up: a Hilt activity whose application is not the `@HiltAndroidApp` class fails with "Hilt Activity must be attached to an @HiltAndroidApp Application", and when the application object is a plain `Application`, the message asks whether you forgot the `android:name` attribute on `<application>` in the manifest. ## Field injection rules 1. Injected fields **cannot be private**: the generated code outside your class assigns them, so Hilt reports a compile error for a private field. In Kotlin, write `@Inject lateinit var`. 2. Fields are injected **during `super.onCreate()`** in an activity, so reading them in a property initializer or before that call sees an uninitialized `lateinit` property. 3. An **abstract** base class with its own `@Inject` fields does not need `@AndroidEntryPoint`; annotate the concrete subclasses and the base class's fields are injected with them. 4. Each activity instance gets its own `ActivityComponent` instance; the same is true per fragment instance. ## Diagnosing a setup failure - **Crash on the first screen with the `@HiltAndroidApp` message**: check the manifest's `android:name` and that the annotated class is the one declared. - **Crash when a fragment is added**: find the host activity in the message and annotate it, or move the fragment to a Hilt activity. - **`lateinit property has not been initialized`** in an activity: something read the field before `super.onCreate()`. - **A compile error on a field**: it is private, or no binding exists for its type; constructor-inject the type or provide it from a module.
- Why does Hilt refuse to inject a private @Inject field?Field injection is done by generated code that lives outside your class and assigns the field directly. It cannot reach a private field, so Hilt reports a compile error instead of falling back to reflection. In Kotlin the idiom is a non-private `@Inject lateinit var`.
- A BaseActivity shared by several screens declares its own @Inject fields; does it need @AndroidEntryPoint?Not if it is abstract. Annotate each concrete activity with `@AndroidEntryPoint`; Hilt injects the inherited fields of an abstract base class along with the subclass's own. Putting the annotation on the concrete classes keeps one generated base class per real screen.
- In a Compose app, which classes get @AndroidEntryPoint?The root `ComponentActivity`, not the composables. It is the single entry point for the UI hierarchy; screens obtain Hilt ViewModels with `hiltViewModel()` and receive everything else through those ViewModels. Services, receivers and any remaining fragments still carry their own annotation.
- Every class with an @Inject constructor also needs @AndroidEntryPoint.
- @HiltAndroidApp can go on the launcher activity instead of the Application.
- A Hilt fragment works in any activity because it has its own component.
- Injected fields are already set before super.onCreate() is called.
- Hilt fields may be private because Hilt injects them by reflection.
- A missing @AndroidEntryPoint on the host activity is caught at compile time.