Skip to content
AppDues
Log in
Contact salesSign up

Hilt SDK Lifecycle Management for Android: Scoping, Cleanup, and Tests

Third-party Android SDKs — billing, analytics, subscriptions — each bring their own initialization and shutdown rules. When those rules don't line up with the Activity or ViewModel lifecycle, you get one of two failures: resources that never get released, or resources released mid-flight during a rotation. Hilt's component tree and its retained lifecycle callbacks give you a declarative way to bind an SDK's lifetime to a scope you choose, instead of scattering manual close() calls across screens.

Why SDK lifetimes drift from Android lifetimes

An SDK configured in Application.onCreate() and never closed keeps its connections, caches, and listeners for the whole process. An SDK configured in Activity.onCreate() and closed in onDestroy() may be torn down during a configuration change even though the user is still on the same screen. Manual tracking — a lateinit field, an isFinishing guard in onDestroy — works, but it has to be repeated in every Activity that touches the SDK, and it is easy to forget. Hilt replaces that repetition with scoping plus a cleanup callback.

The Hilt component tree, mapped to Android lifetimes

Hilt's predefined components nest according to Android's own lifecycle. The application-level SingletonComponent sits at the top; ActivityRetainedComponent survives configuration changes; ActivityComponent, FragmentComponent, ViewComponent, and ViewModelComponent hang below. Each component has a matching scope annotation, and that annotation is what decides when your SDK is created and when it is destroyed. The component tree itself is delivered as a protected module (code0003) alongside this page.

How automatic cleanup actually fires

Hilt exposes cleanup through the RetainedLifecycle interface, implemented by ActivityRetainedLifecycle and ViewModelLifecycle. You register an OnClearedListener; Hilt calls it once, on the main thread, when the retained component is cleared. The internal RetainedLifecycleImpl enforces three rules: all listener operations must run on the main thread (ThreadUtil.ensureMainThread()), listeners are stored in a plain HashSet because single-threaded access removes the need for synchronization, and adding or removing a listener after dispatch throws IllegalStateException with a message describing the race condition. The interface and implementation are delivered as protected modules (code0004, code0005).

Why cleanup waits for finish, not rotation

Hilt does not reinvent lifecycle tracking. ActivityRetainedComponent is held inside an ActivityRetainedComponentViewModel, and Android's ViewModelStore keeps that ViewModel across configuration changes. Only when the Activity truly finishes does the store clear the ViewModel, which calls onCleared(), which dispatches the Hilt callbacks. The practical consequence: your cleanup listener fires on finish, not on rotation. The bridge code is delivered as protected module code0006.

Scope decision checklist

Use this to pick a scope before writing the module. It is a decision aid, not a benchmark.

  • Subscription or billing status is read on many screens and the SDK is core to the app → @Singleton in SingletonComponent. The instance lives for the process and is never disposed; that is intentional, not a leak.
  • The SDK is used by one feature area and should survive rotation but not the whole app → @ActivityRetainedScoped in ActivityRetainedComponent, with a cleanup listener that calls close().
  • Each ViewModel needs its own isolated instance or its own configuration → @ViewModelScoped in ViewModelComponent. Expect one SDK instance per ViewModel, and therefore one billing connection per ViewModel.
  • The SDK should only exist for some users → provide a nullable type and inject Purchases? so callers handle the absent case.
  • The SDK is used once in a settings screen (a tip jar, for example) → application-wide scoping is usually the wrong trade; prefer a narrower scope or lazy initialization.

Three different failures, three different fixes

These look similar in a bug report but have different causes.

  • Cumulative leak: an SDK without singleton protection is initialized per Activity and never closed. Each visit adds an instance, an event buffer, and a network queue. Fix: scope the SDK and register a cleanup listener.
  • Premature disposal: close() is called in onDestroy() without an isFinishing check, so a rotation tears down an SDK the user still needs. Fix: let Hilt's retained lifecycle decide when to dispatch.
  • Duplicate configuration: configure() is called with a different API key or user ID, so a second instance replaces the singleton while the first still holds memory. Fix: keep configuration stable per scope, and close the old instance explicitly when you intentionally replace it.

The Purchases SDK's singleton protection is not universal

The Purchases SDK returns the existing instance when configure() is called again with the same configuration, so the ActivityRetainedScoped and ViewModelScoped patterns will not multiply instances under an identical API key. Different configurations do create a new instance and replace the singleton, and the previous one stays in memory until close() is called. Many other SDKs — Firebase Analytics, Amplitude, Mixpanel, and various payment SDKs — have no such guard and will create a fresh instance on every initialize call. The scoping patterns matter regardless, because they also handle configuration changes and give you one consistent cleanup path across every SDK in the app. The configure implementation is delivered as protected module code0012.

Separate debug and release configuration

Hilt processes each build variant independently, so a debug module and a release module do not collide. In debug builds you can point the SDK at a test key, enable verbose logging, and disable automatic purchase sync for local testing. The source article also mentions StoreKit Testing (Test Store) as a way to simplify subscription testing without connecting to real App Store servers; that is an iOS mechanism, so treat it as background rather than a working Android test path. In release mode you set the real private key so users can purchase the products, and automatic sync stays on. The variant-specific module is delivered as protected module code0011.

What initialization and cleanup actually cost

The source article presents the following figures as typical values without a stated methodology or verification date; treat them as illustrative estimates and re-measure on your own devices and SDK version.

  • Cold initialization: roughly 50–100 ms, including the Google Play Billing connection.
  • Warm initialization: roughly 10–20 ms when the Billing Service is already bound.
  • Cleanup: roughly 10–50 ms, covering Billing disconnect, pending query cancellation, and cache clearing.
  • Singleton memory: about 500 KB, flat across screen visits because the same instance is reused.
  • ActivityRetainedScoped memory: about 500 KB at a time, freed and reallocated per screen.
  • No cleanup across 10 screens: about 5 MB accumulated from 10 leaked instances.

Initialization blocks the calling thread, so it can hit the main thread; cleanup runs synchronously inside ViewModel.onCleared(). Lazy initialization on a background dispatcher moves the cost off the main thread, and background cleanup is possible but risks not completing before the process ends.

Testing the lifecycle wiring

Three layers cover the lifecycle contract. A unit test with HiltAndroidRule captures the registered OnClearedListener and invokes it, then verifies close() was called. An integration test launches the Activity, triggers injection, closes the scenario, and checks cleanup through memory or state inspection. A fake module annotated with @TestInstallIn replaces the production module so tests never touch the real SDK. The test scaffolding is delivered as protected modules code0023, code0024, and code0025.

Coordinating several SDKs with one cleanup order

Dagger's graph guarantees that Purchases is constructed before Analytics when Analytics depends on it, so initialization order is automatic. Cleanup order is not: listeners fire in registration order, and relying on that is fragile. A small coordinator that injects both SDKs and the ActivityRetainedLifecycle, registers a single listener, and calls analytics.close() then purchases.close() makes the order explicit and testable. The coordinator is delivered as protected module code0027.

Hilt scope comparison for third-party SDKs
ScopeComponentLifetimeSurvives rotationCleanup needed
@SingletonSingletonComponentApplication creation to destructionYesNo — intentional process lifetime
@ActivityRetainedScopedActivityRetainedComponentActivity creation to finishYesYes — register OnClearedListener
@ActivityScopedActivityComponentActivity creation to destructionNoYes
@ViewModelScopedViewModelComponentViewModel creation to clearedYesYes — register OnClearedListener
@FragmentScopedFragmentComponentFragment creation to destructionNoYes

Scope lifetimes are Hilt framework behavior; the cleanup column reflects the patterns in this guide, not a framework requirement.

Frequently asked questions

Does Hilt cleanup run when the screen rotates?

No. Hilt's retained lifecycle callbacks are dispatched through ViewModel.onCleared(), which fires when the Activity finishes, not during a configuration change. A rotation reuses the same ActivityRetainedComponent and the same SDK instance.

Can I register a cleanup listener from a background thread?

No. addOnClearedListener and removeOnClearedListener are main-thread operations enforced by ThreadUtil.ensureMainThread(). Posting from a background thread can race with dispatch and throws IllegalStateException.

If the Purchases SDK already prevents duplicate instances, why scope it?

Singleton protection only covers configure() calls with an identical configuration. Scoping still matters because it guarantees close() runs when the scope ends, handles configuration changes correctly, and gives you one pattern that also works for SDKs without that protection.

What does ViewModelScoped cost compared with a shared instance?

Each ViewModel gets its own SDK instance and therefore its own Google Play Billing connection. The original reference figures put each connection at roughly 200–500 ms of initialization time and a few KB of memory, so a single shared instance is usually more efficient unless isolation is required.