Advanced Android interview questions
132 questions from the Advanced lessons. Open a question to see the junior, mid and senior answers. Each one links to the lesson that explains it.
Architecture at scale
When would you skip the domain layer in an Android app?
- Junior
- When the app or screen is simple, like a list or a settings screen, the ViewModel can call the repository directly. Google's architecture guide says the domain layer is optional.
- Mid
- I skip it when business rules are few and only one ViewModel uses them. A use case that just calls one repository method with no logic is a pass-through and only adds indirection. I add a use case when several ViewModels need the same rule, or when one operation combines several repositories.
- Senior
- It is a per-feature decision, not a project-wide one. Simple screens call repositories directly; flows with shared rules, like checkout pricing or onboarding eligibility, get use cases. I would rather extract a use case when the second caller appears than create pass-throughs up front, because moving logic out of a ViewModel into a use case later is a small, mechanical refactor. I make the rule explicit in the team's architecture notes so reviews do not argue about it every time.
How does Google's recommended architecture differ from Uncle Bob's Clean Architecture?
- Junior
- Both separate UI, business logic and data. Google calls them the UI layer, the optional domain layer and the data layer.
- Mid
- In Clean Architecture dependencies point inward: the domain defines repository interfaces and the data layer implements them, so the domain depends on nothing. In Google's guide the domain layer sits between UI and data and depends on the data layer, and the domain layer itself is optional.
- Senior
- The difference shows up in modules and boilerplate. With the dependency rule, :core:domain is pure Kotlin and :core:data depends on it, which keeps business rules free of data libraries but needs an interface and a DI binding per repository. Google's style has fewer files and lets ViewModels use repositories directly. I choose based on the team: a large codebase with several data implementations or Kotlin Multiplatform sharing benefits from the strict rule; a typical app is fine with Google's layering plus interfaces only where tests or alternatives need them.
What is the difference between a use case and a repository method?
- Junior
- A repository gets and stores one type of data from sources like the network or a database. A use case is a business operation that uses one or more repositories and applies a rule.
- Mid
- A repository method is about data: getUser(id), observeOrders(). A use case is about an action the product cares about: GetEligibleOffersUseCase, which might combine the user, their orders and a pricing rule. If the use case has no logic beyond calling one repository method, it is a pass-through.
- Senior
- Repositories own data concerns: caching, the single source of truth, mapping DTOs and entities, and syncing. Use cases own business rules and coordination across repositories, and are usually stateless classes with an operator invoke. A good test: if a product manager would describe the rule (a user is eligible if their email is verified and onboarding is complete), it belongs in a use case; if it is fetch, cache and map, it belongs in the repository.
How do you test a ViewModel that calls a repository?
- Junior
- Create a fake repository that returns test data, pass it to the ViewModel's constructor, call the ViewModel function, and check the state.
- Mid
- The fake implements the repository interface and returns fixed values or a Flow. I use runTest from kotlinx-coroutines-test, and because viewModelScope runs on Dispatchers.Main I replace it with Dispatchers.setMain(StandardTestDispatcher()) in a test rule. Then I call the function, advance the dispatcher and assert on the StateFlow value.
- Senior
- I prefer fakes to mocks for repositories because they behave like the real thing, for example a fake backed by a MutableStateFlow re-emits when its data changes. I test the error path by making the fake throw and asserting the UI state. Repositories get their own tests with a fake API or MockWebServer and an in-memory Room database. If a ViewModel test needs a real network, disk or Android framework classes, that tells me the layering is wrong.
Why would you add a domain layer to an Android app?
- Junior
- To hold business rules in use cases instead of ViewModels. Use cases are small classes that are easy to unit test, and several screens can reuse the same one.
- Mid
- Google's guide recommends it for complex logic or logic reused by several ViewModels. Each use case does one thing, has an operator invoke, gets repositories through its constructor and is main-safe. The ViewModel then only maps results to UI state, which keeps it small.
- Senior
- It is a trade-off between indirection and reuse, so I decide per feature. I add use cases when a rule is shared or when one operation coordinates several repositories, and I skip them for simple screens. I also choose the dependency direction deliberately: Google's layering lets use cases depend on repositories directly, while Clean style puts repository interfaces in a pure Kotlin domain module, which costs a binding per repository but keeps data libraries out of the business rules. Either way use cases stay stateless and do not own scopes.
When is a domain layer NOT worth it?
- Junior
- When the app is mostly showing and editing data with few rules. The ViewModel can call the repository directly.
- Mid
- When every use case would be a one-line pass-through to a repository, with no validation, combination or transformation. That adds files and review time without making anything easier to test, because the repository can already be faked.
- Senior
- Also when the only reason is a diagram. In a small app or an early product, I keep logic in ViewModels and repositories and extract a use case when a second caller appears; that refactor is cheap and mechanical. What I watch for is the opposite failure: the same rule copied into several ViewModels. That is the signal the domain layer has started paying for itself.
How do you test a use case that returns a Flow?
- Junior
- Use runTest from kotlinx-coroutines-test, give the use case a fake repository, collect the Flow with first() or toList() and assert on the values.
- Mid
- The fake repository is backed by a MutableStateFlow so the test can push new values. I read emissions with Turbine (test { awaitItem() }) or collect in backgroundScope, because a collector launched with plain launch on an endless Flow keeps runTest from finishing. I test the success case, the rule failing and the upstream throwing.
- Senior
- I also test lifecycle behaviour: after the collector is cancelled, writes to the fake must not trigger more work, which catches use cases that secretly cache a hot StateFlow. If the use case switches dispatchers for CPU-heavy work, I inject the dispatcher so the test can pass a StandardTestDispatcher and stay deterministic. And I check that cancellation propagates, since a runCatching around a suspend call is an easy bug to miss.
What is the difference between a use case and a repository method?
- Junior
- A repository method gets or stores data. A use case applies a business rule on top of that data, for example checking that a user has a display name before returning it.
- Mid
- The repository owns data access: sources, caching, the single source of truth and mapping DTOs or entities. The use case owns business rules and coordination, such as validation or combining two repositories. If a use case has no rule, it is a pass-through.
- Senior
- The line blurs, so I use a test: would the product owner describe this rule? If yes, it belongs in a use case. If it is fetch, cache and map, it belongs in the repository. A use case that calls two repositories and merges their results is legitimate orchestration; mapping a Room entity to a model is still data-layer work even when it lives in a class named UseCase.
How do you structure a multi-module Android project?
- Junior
- An app module, feature modules like :feature:home and :feature:profile, and core modules for shared UI, networking and data. The app module depends on the features, and features depend on core.
- Mid
- I follow Google's modularization guide: app, feature, data and core modules, with dependencies pointing from app toward core. Features do not depend on each other. Where a feature needs another area's contract, I split that area into an api module with interfaces and models and an implementation module with the concrete classes; consumers depend on the api module, and the app module pulls in the implementation so Hilt can bind it.
- Senior
- I size modules to team ownership and measured build cost rather than to a diagram. Convention plugins in build-logic keep build files consistent, implementation is the default configuration, and implementation details are internal so boundaries are enforced by the compiler. I keep the graph shallow and wide, because a long chain of modules limits parallel builds, and I add a CI check that rejects feature-to-feature dependencies. Before and after a split I compare Build Scans.
What is the difference between api and implementation in Gradle?
- Junior
- implementation makes a dependency visible only to the module that declares it. api also makes it visible to modules that depend on this module.
- Mid
- If module A declares api(project(":core:model")), a module B that depends on A can compile against :core:model types without declaring it. With implementation, B cannot. Use api when A's public functions or classes use those types; otherwise use implementation.
- Senior
- Both end up on the runtime classpath and in the APK, so the difference is compile visibility and recompilation. An implementation dependency is not on consumers' compile classpath, so when it changes, the consumers do not need to recompile; an api dependency is, so its changes ripple outward. For published libraries this maps to compile versus runtime scope in the published metadata. I audit with :module:dependencies --configuration releaseCompileClasspath and downgrade api to implementation wherever the type does not appear in public signatures.
When would you NOT add a new module?
- Junior
- When the code is small and changes together with the code around it. A module adds a build file and wiring without a clear benefit.
- Mid
- When the split is per screen or per tiny feature. Each module adds configuration time, a build file and DI wiring. If two screens always change together, they belong in the same feature module. I add a module for a separate team's code, for a reusable piece like the design system, or when build measurements show a hotspot that a split would help.
- Senior
- I look at ownership, change patterns and measured build impact. A module whose public API changes in every PR does not isolate anything, because its consumers recompile anyway. A module touched by one person, rarely, adds cost without benefit. I check Build Scans for configuration time and cache hits before proposing more modules, and I am willing to merge modules back when the boundary turned out wrong.
How do you handle code shared by two feature modules?
- Junior
- Move it into a core module that both features depend on, for example :core:ui for a shared component or :core:model for a shared data class.
- Mid
- If it is a contract such as AuthRepository, put the interface in an api module that both features depend on, and the implementation in an implementation module that only the app module depends on. Hilt binds them. Importing a class from another feature couples the two and invites cycles.
- Senior
- First I ask whether it is really shared or whether the feature boundary is wrong. Truly shared building blocks go to core; a small helper used by two features can be duplicated rather than creating a module for it. I avoid a growing :core:common grab bag, because every module depends on it and any change recompiles everything; splitting it by purpose, like :core:model and :core:ui, keeps changes local.
How do you navigate between two feature modules in a multi-module Android app?
- Junior
- The feature modules do not depend on each other. Each one exposes a NavGraphBuilder extension with its screens, and the app module puts them all into one NavHost.
- Mid
- Each feature exposes a @Serializable route, a NavController.navigateToX function and a NavGraphBuilder extension. When profile needs to open settings, profileScreen takes an onOpenSettings lambda, and the app module passes navController::navigateToSettings. Only the app module knows every feature.
- Senior
- Callbacks wired in the app module are the default, because they keep features fully independent and make screens easy to preview with empty lambdas. If a feature must construct another feature's route itself, I split routes into small api modules (:feature:settings:api) and keep screens internal in the implementation module. I enforce the rule with a CI check against feature-to-feature dependencies, and I keep route arguments to IDs so saved state stays small and destinations load fresh data.
What does @Serializable give you in Navigation Compose?
- Junior
- Type-safe routes. Instead of route strings you navigate with objects like ProfileRoute(userId), so typos become compile errors.
- Mid
- The Kotlin serialization plugin generates a serializer for the route class at compile time. Navigation uses it to build the route and its arguments, and toRoute() on a NavBackStackEntry or a SavedStateHandle turns the arguments back into the typed object. Primitive types, strings and enums work out of the box.
- Senior
- Argument names and types are checked by the compiler, and the same route class is used to register, navigate and read arguments, so they cannot drift apart. The trade-off is that custom types need a NavType in typeMap, which is a hint to pass an ID instead. Routes still end up in saved state, so they should be small, and changing a route class is a change to every caller, which is why I keep routes stable and minimal.
Why shouldn't a feature module depend on another feature module?
- Junior
- It can create circular dependencies, and it ties two features together so they cannot be changed separately.
- Mid
- If feature A depends on feature B, every change to B recompiles A, and A cannot be built or tested without B. When B later needs something from A, the graph has a cycle and Gradle refuses to build.
- Senior
- It turns team boundaries into a web. Features stop being independently buildable, ownership blurs, and B's internals leak to A unless everything is carefully internal. Keeping features as leaves under the app module also keeps the graph wide and shallow, which lets Gradle build more modules in parallel. Contracts go into core or api modules, and navigation goes through the app module.
How should a ViewModel trigger navigation?
- Junior
- It should not call navController.navigate() itself. The screen does the navigation.
- Mid
- For a simple click, the screen calls its navigation lambda directly. When navigation depends on a result, like after saving a form, the ViewModel exposes it in UI state, for example isSaved = true, and the screen calls onSaved() when it sees that state.
- Senior
- Google's guidance is to model these events as UI state instead of sending them through a Channel or SharedFlow, because a one-off event can be lost if it is emitted while nobody is collecting. The screen reacts to the state in a LaunchedEffect, calls the navigation lambda, and tells the ViewModel the event was handled if the state must be reset. This keeps the ViewModel free of NavController, makes it easy to unit test, and keeps navigation in the layer that owns the back stack.
How does fetchAndActivate work, and why might you call fetch and activate separately?
- Junior
- fetchAndActivate downloads the latest parameters from Firebase and makes them active in one call. It returns a Task<Boolean> that is true when new values were activated. Reads with getBoolean and friends always return the active values.
- Mid
- fetch downloads values but they do not take effect until activate. Separating them lets you control timing: for example, activate at startup the values fetched during the previous session, then fetch in the background for next time, so the UI never changes under the user. Fetches respect the minimum fetch interval, 12 hours by default, and return cached values inside it.
- Senior
- I choose the loading strategy per app: fetchAndActivate behind a short splash when flags must be fresh at startup, or activate-cached-then-fetch when startup time matters more. For kill switches I add real-time updates with addOnConfigUpdateListener, which fetches new templates automatically, and I call activate at a safe point. All of it sits behind a FeatureFlags interface so ViewModels read plain booleans and tests use fakes, and I log value sources in debug builds to catch devices running on defaults.
How do you implement a kill switch on Android?
- Junior
- A Remote Config parameter like checkout_v2_kill_switch with an in-app default of false. The code checks it first and turns the feature off when it is true.
- Mid
- The kill switch is checked in the same function as the feature flag, before it, so it wins whatever the rollout percentage says. Its default is false so the feature works when Remote Config is unavailable. The flag is read in the ViewModel or data layer, not scattered through Composables.
- Senior
- The hard part is propagation. A switch only helps if devices see it soon: within a 12-hour minimum fetch interval they will not. So I either use real-time Remote Config or fetch at every startup with a short interval, and I decide what happens to users already inside the feature (usually the switch applies on the next screen entry, not mid-flow). The kill-switch path is tested like any other path, and turning one on is part of the incident runbook.
How do you test code that depends on feature flags?
- Junior
- Hide Remote Config behind an interface and give tests a fake that returns fixed values, so tests do not need the network.
- Mid
- Unit tests use a fake FeatureFlags and cover each branch: flag on, flag off, and kill switch on. Debug builds use a minimum fetch interval of 0 so testers see console changes immediately, and a debug menu can override flags locally.
- Senior
- Each flag doubles the paths through a feature, so I keep the number of live flags small and test the combinations that matter, especially the kill-switch path and the in-app defaults, since those are what users get when Firebase is unavailable. A unit test checks that every key the app reads has a default. UI tests run against the fake with explicit values rather than a shared Firebase project, so they are deterministic.
When and how do you remove a feature flag?
- Junior
- After the feature is at 100% and stable, delete the old code path and the flag check.
- Mid
- First a release that removes the old path and the flag check, so the new behaviour is unconditional. The console parameter stays until older app versions that read it are rarely used, because deleting it sends those versions back to their in-app defaults.
- Senior
- I treat flags as debt with an owner and an expiry date set when the flag is created. Removal is a two-step process: code first, then the console parameter after checking version distribution in Play Console. Setting a shipped feature's in-app default to the rolled-out value in the meantime makes the parameter deletion safe. Periodic cleanups go through the list of flags at 100% and open removal tasks for each.
Compose internals
What is recomposition in Jetpack Compose, and how does Compose decide to skip a composable?
- Junior
- Recomposition is Compose calling a composable again because state it read changed. If a child's parameters have not changed, Compose can skip it and keep its old UI.
- Mid
- The compiler generates code that stores each parameter and compares it with the previous value. Stable parameters are compared with equals and unstable ones with === under strong skipping, which is the default from Kotlin 2.0.20. If all match, the function body is skipped. Lambdas are remembered automatically so they compare equal across recompositions.
- Senior
- Restartable functions get a restart scope, so only the scopes that read changed state are invalidated; skipping then prunes children whose arguments compare equal. Under strong skipping every restartable function is skippable, so the usual cause of extra work is new instances: collections built in the body, objects mapped on every emission. I check Layout Inspector recomposition counts, read composables.txt for unstable parameters, and fix the source of new instances rather than annotating types.
What is the difference between @Stable and @Immutable?
- Junior
- @Immutable means nothing in the object changes after it is created. @Stable means it can change, but Compose is told when it does.
- Mid
- Both make the compiler treat the type as stable, so it is compared with equals. @Immutable promises all public state is fixed after construction. @Stable allows mutable properties as long as they are backed by snapshot state such as mutableStateOf, so readers are invalidated when they change. Classes with only val properties of stable types are inferred stable and need neither.
- Senior
- They are promises the compiler cannot check, much like !!. If you put @Immutable on a class with a var or a MutableList, Compose may skip a child whose data changed and the UI goes stale. I use them for small types the compiler cannot infer, such as classes from a non-Compose module, and only when equals is cheap. For collection-holding models I usually leave them unstable so Compose compares by instance instead of walking every element.
A LazyColumn row recomposes when unrelated state changes. How do you find and fix it?
- Junior
- Use Layout Inspector to see recomposition counts. Look for a list or object created inside the composable and cache it with remember or move it to the ViewModel.
- Mid
- Layout Inspector shows which composables recompose and which skip. Then I enable compiler reports with reportsDestination in the composeCompiler block and check composables.txt for unstable parameters. Most often the parent builds a new list or maps models on every pass, so I preserve the instance. I also check that items have stable keys so rows are matched correctly.
- Senior
- I separate causes: a new instance every pass, an unstable class from a module without the Compose compiler that is re-created on each emission, or a fast-changing value read in composition that should be read in layout or draw. For the second, a stability configuration file or UI-model mapping lets equals work. I verify with a Macrobenchmark frame timing test, because a lower recomposition count does not always mean a faster frame.
What does strong skipping mode change, and what can go wrong?
- Junior
- It is on by default from Kotlin 2.0.20. Composables with unstable parameters can now be skipped, and lambdas are remembered automatically.
- Mid
- Before it, a composable with any unstable parameter was never skippable and re-ran whenever its parent did. Now unstable parameters are compared by instance with ===, stable ones with equals, and every lambda is wrapped in remember keyed on its captures. Much manual work, like remembering lambdas or wrapping lists, is no longer needed.
- Senior
- The risk is code that mutates an unstable object in place and passes the same instance again: before, the child re-ran anyway; now it is skipped and shows stale data. The fix is immutable data with new instances on change, or snapshot state inside the object. You can opt out per function with @NonSkippableComposable or per lambda with @DontMemoize. I also review older advice in the codebase, since converting everything to ImmutableList now forces element-by-element equals.
What is the difference between mutableStateOf and derivedStateOf, and when is derivedStateOf worth using?
- Junior
- mutableStateOf holds a value you write, and Compose recomposes readers when it changes. derivedStateOf computes a value from other state and is read-only.
- Mid
- derivedStateOf caches its result and notifies readers only when the result changes, not every time an input changes. It is worth using when inputs change much more often than the output, such as firstVisibleItemIndex > 0 for a scroll-to-top button. It must be wrapped in remember inside a composable.
- Senior
- It is a filter on invalidation. If the derived value changes as often as its inputs, it costs extra bookkeeping with no saving, so for a query filter I use remember with keys or move the work to the ViewModel. I also watch for captured non-state values inside remember { derivedStateOf { } }: they are frozen unless they are remember keys, which is a common source of stale UI.
How does snapshotFlow work and when would you use it?
- Junior
- snapshotFlow turns Compose state into a Flow. It emits again when the state read inside the block changes. I use it inside LaunchedEffect to react to state, for example to log the scroll position.
- Mid
- The block runs and the state objects it reads are recorded. When one of them changes, the block runs again, and the new result is emitted only if it differs from the previous one. It is cold, so each collector runs its own observation, and collecting in LaunchedEffect ties it to the composable's lifetime.
- Senior
- Under the hood it registers an apply observer and re-runs the block when an applied change touches something it read, so it can skip intermediate values when several writes land together. That is fine for analytics or saving drafts, but it should not be used for logic that must see every value. I combine it with operators like debounce or filter, use rememberUpdatedState for callbacks it calls, and keep app-wide state in a ViewModel StateFlow rather than in Compose state.
What is a snapshot in Compose?
- Junior
- A snapshot is a consistent view of all Compose state at one moment. Compose uses them internally so the UI sees a complete set of changes, not half of them.
- Mid
- Snapshot.takeSnapshot() returns a read-only snapshot; inside enter { } you read state values as they were when it was taken, even if other code changes them later. A mutable snapshot isolates writes until apply() is called, and Snapshot.withMutableSnapshot { } wraps that pattern. Code outside any explicit snapshot reads and writes the global snapshot.
- Senior
- It is multi-version concurrency control: state objects keep records per snapshot, so a snapshot can read old values while newer ones are written elsewhere. Composition runs in its own mutable snapshot and applies its writes at the end, which is why writing state during composition is dangerous. When two snapshots change the same object, apply checks for a conflict and the state's mutation policy can merge it, otherwise apply fails. Apply observers then tell the Recomposer which objects changed so it invalidates only the scopes that read them.
Can you write Compose state from a background thread?
- Junior
- Yes. Snapshot state is thread-safe, and the UI updates after the write.
- Mid
- Writes go to the global snapshot, and on Android Compose schedules the apply notification, so readers recompose on the next frame. Still, I usually keep screen state in a ViewModel StateFlow and collect it with collectAsStateWithLifecycle, which keeps updates in one place.
- Senior
- Thread safety covers individual reads and writes, not compound operations. count.value = count.value + 1 from two coroutines can lose an update unless the update runs in a mutable snapshot that detects the conflict, or a single owner serialises updates. For heavy work I compute off the main thread and publish a single new value, rather than mutating a SnapshotStateList item by item from several coroutines.
How do you enable Compose compiler reports, and what do they contain?
- Junior
- Apply the Compose compiler Gradle plugin and set reportsDestination and metricsDestination in the composeCompiler block. After a build there are text files listing composables, whether they are skippable, and which parameters are stable.
- Mid
- reportsDestination writes classes.txt, composables.txt and composables.csv per module; metricsDestination writes module.json with totals such as skippableComposables. composables.txt shows restartable and skippable for each function and stable or unstable for each parameter, plus @static or @dynamic for defaults. I generate them from a release build.
- Senior
- I gate them behind a Gradle property or a convention plugin so normal builds stay clean, and turn them on in CI when shared models or the Kotlin version change. Since strong skipping makes almost everything skippable, I mostly look for unstable parameters on hot composables and then check the call site for new instances. I pair the report with Layout Inspector counts and a Macrobenchmark, since the report alone says nothing about runtime cost.
What does strong skipping mode change in the report?
- Junior
- With strong skipping, which is the default from Kotlin 2.0.20, composables with unstable parameters are still marked skippable.
- Mid
- Without it, any unstable parameter made a function restartable but not skippable, so it re-ran with its parent. With it, every restartable function is skippable; unstable parameters compare with === and stable ones with equals, and lambdas are remembered automatically.
- Senior
- The report stops being a list of non-skippable functions and becomes a list of comparison modes. An unstable List parameter is fine if the caller preserves the instance, while making it ImmutableList forces element-by-element equals. So I read the report together with how data flows in: does the repository or ViewModel re-create equal objects on each emission? That decides whether to preserve instances, mark a flat model stable, or leave it alone.
A parameter is unstable because its class lives in a pure Kotlin module. What are your options?
- Junior
- Add the class to a stability configuration file, or annotate it with @Immutable if that module can depend on the Compose runtime.
- Mid
- Options are: list it in the stability configuration file passed with stabilityConfigurationFiles, enable the Compose compiler in that module, annotate it, or map it to a UI model in the UI module. First I check whether it matters: if callers pass the same instance, === already lets it skip.
- Senior
- I prefer the configuration file for flat, immutable models because it keeps Compose out of the domain module. I do not list classes holding collections, since equals would walk every element; for those I preserve instances or wrap them in a UI model. Every entry is a promise, so I review the file like code and avoid broad wildcards over packages with mutable types.
What makes a composable restartable, and what does that mean?
- Junior
- Restartable means Compose can re-run just that function when state it read changes, without re-running its parent.
- Mid
- Most composables that return Unit and are not inline are restartable; the compiler gives them a restart scope. Composables that return a value, like a remember helper, and inline composables such as Column's content are not; their reads invalidate the nearest restartable parent. @NonRestartableComposable opts out.
- Senior
- This explains where recomposition lands. A state read inside Column's inline content invalidates the enclosing function, so a fast-changing read there re-runs more than expected. Moving that read into a small child composable or a lambda modifier narrows the scope. Restartability has nothing to do with side effects in the body; those are bugs because composition can run many times or be discarded.
How do you build a custom layout in Jetpack Compose?
- Junior
- Use the Layout composable with content and a measure lambda. Measure each child, then call layout(width, height) and place each child with placeRelative.
- Mid
- The MeasurePolicy gets List<Measurable> and Constraints. I derive child constraints (often relaxing the minimums), measure each child once, compute my size and coerce it into the incoming constraints, then place children inside layout(). placeRelative keeps RTL correct.
- Senior
- The contract is one measure per child per pass, constraints down and sizes up, which is what keeps Compose layout linear. When a child's size must influence another child's constraints I use intrinsics, or SubcomposeLayout if content depends on measurement, accepting its extra cost. I also handle Constraints.Infinity for scrolling parents and test RTL and font scaling with screenshot tests.
Why is Modifier.Node preferred over Modifier.composed?
- Junior
- Google recommends Modifier.Node for custom modifiers. composed is no longer recommended because it is slower.
- Mid
- composed runs composition work for every element it is applied to, and that work cannot be skipped. A node-based modifier uses a ModifierNodeElement that is compared with equals; if it is equal, nothing happens, otherwise update() changes the existing node. The node lives as long as the layout node and can hold state.
- Senior
- Nodes are long-lived objects attached to the layout node, with onAttach and onDetach, a coroutineScope for animations, and invalidateMeasurement or invalidateDraw to re-run only the needed phase. That avoids composition entirely for things like a shimmer. The cost is that you cannot call composables inside a node; if you need a CompositionLocal you read it with currentValueOf in a node implementing CompositionLocalConsumerModifierNode.
What do Constraints mean, and what happens if a layout ignores them?
- Junior
- Constraints are the minimum and maximum width and height a parent allows. A child should choose a size inside them.
- Mid
- They flow from parent to child, and sizes flow back up. If a layout reports a size outside its constraints, Compose coerces the size and centers the content in the allowed space, so the result looks offset or clipped. maxWidth or maxHeight can be infinite inside a scrolling container.
- Senior
- Most bugs come from passing constraints through unchanged: a parent minimum forces every child to stretch, and an infinite max height breaks anything that wants to fill the space, which is why a LazyColumn inside verticalScroll throws. In a custom layout I decide child constraints deliberately, coerce my own size, and write a test with fixed constraints to check the result.
What is the difference between place and placeRelative?
- Junior
- placeRelative flips the x position in right-to-left layouts; place does not.
- Mid
- Both place a Placeable inside the layout. placeRelative mirrors x based on the layout direction, so start-aligned content moves to the right edge in RTL. place uses the same x in every direction, which is right for things that must not mirror, like a chart's time axis in some designs.
- Senior
- I default to placeRelative and treat every place call as a decision to document. I check RTL with a preview or screenshot test using LocalLayoutDirection set to Rtl, because mirroring bugs rarely show up in manual testing in LTR locales.
What is the difference between animateFloatAsState and Animatable?
- Junior
- animateFloatAsState animates to a target whenever the target changes. Animatable lets me start, snap and stop animations myself from a coroutine.
- Mid
- animateFloatAsState is declarative: I pass a target and it returns State<Float>, and changing the target mid-way continues smoothly. Animatable is imperative: animateTo, snapTo and animateDecay are suspend functions, a new animateTo cancels the previous one, and I can pass an initial velocity. I use Animatable for gestures and sequences.
- Senior
- Both run on the frame clock and keep velocity on interruption with spring specs. The real difference is who owns the target. With animateFloatAsState the target comes from state each recomposition, which fits UI that mirrors state. With Animatable my code owns it, so I can snap to a finger during a drag, then animateTo or animateDecay with the VelocityTracker velocity on release, and run steps sequentially in one coroutine. I keep the Animatable in remember and launch from rememberCoroutineScope or LaunchedEffect.
How do you keep animations from causing jank in Compose?
- Junior
- Read animated values inside lambda modifiers like graphicsLayer so the composable does not recompose every frame.
- Mid
- Per-frame values should be read in layout or draw: offset { } for position, graphicsLayer { } for alpha, scale, rotation and translation, drawBehind for custom drawing. I also avoid animating layout properties like size when a scale would look the same.
- Senior
- I think in phases: composition is the most expensive per frame, then layout, then draw. graphicsLayer reads only invalidate the layer's draw, so the composable and its measure are skipped. I check with Layout Inspector recomposition counts and a Macrobenchmark frame timing test, and I keep infinite animations inside the smallest composable so they stop when it leaves the screen.
What happens if you use Modifier.offset(x = animatedX) instead of Modifier.offset { }?
- Junior
- It works, but the composable recomposes on every frame of the animation.
- Mid
- The parameter version reads animatedX while composing, so each frame invalidates the composition scope. The lambda version reads it during placement, so only layout re-runs.
- Senior
- With the lambda the state read is recorded by the layout phase, so a change re-runs placement for that node without recomposing anything. The parameter version also allocates a new modifier each recomposition. It matters most for scroll-linked effects and long lists, where many items animate at once.
When do you use updateTransition instead of several animate*AsState calls?
- Junior
- When several properties should change together because of one state.
- Mid
- updateTransition takes one target state and lets me define animateDp, animateColor and others as children, so they start together and I can tune each spec. It also shows up in Animation Preview, where I can scrub through it.
- Senior
- It gives one timeline and one source of truth: I can query currentState, targetState and isRunning, use MutableTransitionState to start an animation on first composition or react when it finishes, and add AnimatedVisibility or AnimatedContent as children of the same transition. Separate animate*AsState calls cannot be coordinated that way.
What is a deferred read, and why does offset { } help performance?
- Junior
- It means reading state inside a lambda modifier instead of in the composable body. offset { } reads the value during layout, so changing it does not recompose the composable.
- Mid
- Compose records which phase read each state. A read in the body invalidates composition, which then also runs layout and draw. A read in offset { } is recorded by the layout phase, so a change re-runs only layout and draw for that node. graphicsLayer { } and drawBehind { } go one step further and only redraw.
- Senior
- The pattern is to push fast-changing reads as late as possible and as deep as possible: pass () -> T providers down instead of values, and read them in layout or draw lambdas. The limit is that a deferred value cannot change what is composed; if it decides whether a child exists, I convert it to a coarse value with derivedStateOf so composition only re-runs when the threshold flips. I verify with Layout Inspector recomposition counts.
What do key and contentType do in a LazyColumn?
- Junior
- key gives each item a unique id so Compose knows which item is which when the list changes. contentType tells Compose which items look alike.
- Mid
- Without keys, items are identified by index, so remembered state stays with a position after a reorder and the scroll position cannot follow the item when something is inserted above. Keys must be unique and Bundle-compatible on Android. contentType limits composition reuse to items of the same type, which makes reuse cheaper in mixed lists.
- Senior
- Keys are also what make Modifier.animateItem() and scroll anchoring work, so I treat a missing key on a mutable list as a bug. I use stable domain ids, never indexes or hash codes of mutable data. contentType matters most for heterogeneous feeds with headers, ads and rows. Beyond that, I keep item composables light, avoid zero-size placeholders, and make sure item parameters are not re-created on every emission.
When would you use derivedStateOf in a list screen?
- Junior
- When I only care about part of the scroll state, like whether the list is scrolled past the first item.
- Mid
- derivedStateOf { listState.firstVisibleItemIndex > 0 } changes only when the Boolean flips, so a scroll-to-top button recomposes twice instead of on every scrolled item. It must be wrapped in remember.
- Senior
- It is for reducing how often composition sees a value, not for every calculation. If the result changes as often as the input, like the raw scroll offset, I use a deferred read instead. If the input is a plain parameter rather than state, it must be a remember key or the derived state goes stale.
How do you diagnose a janky LazyColumn?
- Junior
- Test in a release build, then use Layout Inspector to see which composables recompose while scrolling. Check that items have keys.
- Mid
- I write a Macrobenchmark scroll test with FrameTimingMetric to get frame durations, and look at a system trace in Android Studio or Perfetto for long composition or layout. Then I check for scroll state read in composition, heavy work in item bodies such as formatting or sorting, missing keys, and unstable item parameters in the compiler report.
- Senior
- I make sure the measurement is honest first: release build, R8, Baseline Profile, a real mid-range device. Then I separate first-scroll jank, which is often missing profiles or image decoding, from steady-state jank from per-frame recomposition. I add trace sections around suspect code, fix the biggest offender, and keep the benchmark in CI. In the field, JankStats or Play vitals show whether the fix helped real users.
Performance and reliability
How does LeakCanary detect a memory leak?
- Junior
- LeakCanary watches objects that should be garbage collected, like destroyed Activities and Fragments, through weak references. If one is still in memory a few seconds later after a garbage collection, it dumps the heap and shows the chain of references that keeps it alive.
- Mid
- When an Activity, Fragment, Fragment view, ViewModel or Service is destroyed, LeakCanary's ObjectWatcher holds it in a weak reference tied to a reference queue. After 5 seconds it runs a GC and checks whether the reference was cleared. If not, the object is retained. When the retained count reaches a threshold (5 while visible, 1 in the background), it dumps the heap, and the Shark library finds the shortest strong reference path from a GC root to each retained object. That path is the leak trace.
- Senior
- Retained is not the same as leaked, which is why LeakCanary waits for a threshold before an expensive heap dump. When reading the trace I look for the transition from Leaking: NO to Leaking: YES; the bad reference is in that span. Then I decide which link to break: usually the static field, the unremoved listener or the long-lived coroutine. For custom objects, such as a presenter that should die with a screen, I call AppWatcher.objectWatcher.expectWeaklyReachable. To stop regressions I run the instrumentation artifact with DetectLeaksAfterTestSuccess in UI tests on CI.
What are the most common memory leak patterns in a Kotlin Android app?
- Junior
- A static field or companion object holding an Activity, a BroadcastReceiver or listener registered but never unregistered, and a Fragment view binding not set to null in onDestroyView. Each one keeps a destroyed screen in memory.
- Mid
- Beyond those, a common Kotlin pattern is a coroutine or Flow collector that writes into a View but runs in GlobalScope or the Fragment's own lifecycleScope, so it outlives the view. The fix is viewLifecycleOwner.lifecycleScope with repeatOnLifecycle. Another is a Handler.postDelayed callback or lambda that captures an Activity and runs long after it is destroyed.
- Senior
- I group leaks by what holds them. Static holders (objects, singletons, caches) are easy to fix with applicationContext or by passing data instead of Context. Lifecycle mismatches (registered in onStart, removed in onDestroy, or a collector in the wrong scope) are harder because they only show after navigation or rotation. Then there are injected long-lived objects: a singleton in the DI graph that receives an Activity Context leaks that Activity, so I check that singletons only take the application Context. I keep LeakCanary in every debug build and leak detection in UI tests so new traces block merges.
How do you handle Fragment view binding correctly?
- Junior
- Declare the binding as a nullable var, inflate it in onCreateView, and set it to null in onDestroyView. This releases the View tree when the view is destroyed.
- Mid
- Use a nullable backing property with a non-null getter that is only valid between onCreateView and onDestroyView. It must be cleared in onDestroyView, not onDestroy, because a Fragment on the back stack has its view destroyed but stays alive itself. Any async work that touches the binding must be scoped to viewLifecycleOwner so it cannot run after the view is gone.
- Senior
- In a codebase with many Fragments I standardise the pattern, for example a small property delegate that clears the binding through viewLifecycleOwner, and I make sure all UI collection uses viewLifecycleOwner.lifecycleScope. I also clear things that point at views but live in Fragment fields, such as setting a RecyclerView adapter to null in onDestroyView. I verify with LeakCanary by navigating forward and back and rotating, and with DetectLeaksAfterTestSuccess in UI tests.
What is the difference between viewModelScope and viewLifecycleOwner.lifecycleScope, and how does each relate to leaks?
- Junior
- viewModelScope is cancelled when the ViewModel is cleared. viewLifecycleOwner.lifecycleScope is cancelled when the Fragment's view is destroyed. Use viewLifecycleOwner.lifecycleScope for code that updates Views.
- Mid
- viewModelScope survives configuration changes and back stack trips because the ViewModel is retained, so it is right for loading data, not for touching Views. If a Fragment launched work in viewModelScope that captured a View or binding, that View would stay alive until the ViewModel is cleared. viewLifecycleOwner.lifecycleScope ends with the view, so it is the correct scope for UI work.
- Senior
- I split responsibilities: the ViewModel launches work in viewModelScope and exposes the result as a StateFlow, and the Fragment collects that StateFlow in viewLifecycleOwner.lifecycleScope with repeatOnLifecycle. The ViewModel never holds a View, a binding or an Activity Context, so its longer life cannot leak UI. I check this with LeakCanary, which also reports cleared ViewModels that are still retained, and I unit test the ViewModel with an injected test dispatcher.
What causes an ANR in Android and how do you debug one?
- Junior
- An ANR happens when the main thread is blocked for too long, usually by I/O or heavy computation, so the app cannot respond to input. I debug it by reading the ANR trace in Play Console and finding what the main thread was doing.
- Mid
- The most common type is the 5-second input dispatch timeout. In the trace I look at the main thread's state: if it is RUNNABLE in my code, it is CPU work or I/O; if it is BLOCKED or WAITING, I find which thread holds the lock it wants. In debug I enable StrictMode for disk and network on the main thread to catch these before release.
- Senior
- I treat the main-thread stack as a symptom and follow the chain: the main thread waits on a monitor held by a background thread, which is itself blocked on a binder call or disk write. I also check startup, because the docs note that slow app startup causes broadcast and execute-service ANRs. In production I collect ApplicationExitInfo with REASON_ANR on the next launch and upload getTraceInputStream() to our crash tooling, so I see full traces for our own sessions alongside Play Console clusters grouped by device, Android version and release.
What are the different ANR timeouts and when do they apply?
- Junior
- The input dispatch timeout is 5 seconds. Broadcast receivers and services have their own, longer timeouts.
- Mid
- Input dispatch and no-focused-window are 5 s. A BroadcastReceiver gets 10 s for a foreground-priority intent and 60 s for a background-priority one on Android 13 and lower. An executing service gets 20 s in the foreground and 200 s in the background. A content provider timeout is whatever the client sets with ContentProviderClient.setDetectNotResponding.
- Senior
- Input ANRs are raised by the system's input dispatcher when the app's window does not finish handling an event in time. Component ANRs are timers in the system server that fire if onReceive or a service's onCreate, onStartCommand or onBind has not finished. Foreground and background priority for broadcasts come from FLAG_RECEIVER_FOREGROUND on the intent, not from whether the app is visible; most broadcasts are background priority. On Android 14+ the broadcast timeouts can stretch (10 to 20 s, 60 to 120 s) when the process is CPU-starved. Knowing the type tells me where to look: input ANRs mean the main thread was busy; receiver ANRs often mean onReceive did too much or startup was slow.
How do you prevent ANRs in production code?
- Junior
- Move I/O and heavy work off the main thread using coroutines with Dispatchers.IO and Dispatchers.Default. Use StrictMode in debug to catch violations early.
- Mid
- I enable StrictMode in debug builds for disk and network on the main thread. Repositories make their own calls main-safe with withContext, so callers never block. I avoid locks that the main thread shares with background threads, keep onReceive tiny by handing work to WorkManager, and use viewLifecycleOwner.lifecycleScope for UI work in Fragments.
- Senior
- Beyond per-call fixes, I make main-safety a rule: every suspend function in the data layer is safe to call from the main thread, and the dispatcher is injected so tests can control it. I watch the user-perceived ANR rate in Android vitals per release and collect ApplicationExitInfo traces for our own analysis. I reduce startup work by deferring initialisation, which also lowers receiver and service ANRs during startup. For shared state I prefer suspending Mutex or a single-threaded owner over synchronized blocks touched by the main thread.
Play Console shows a new ANR cluster. Walk me through your investigation.
- Junior
- I open the cluster in Play Console, read the main-thread stack trace, and find the blocking call in our code. Then I move it to a background thread.
- Mid
- I check the ANR type and the main-thread state in the trace, then look at other threads to see whether one holds a lock the main thread is waiting for. I try to reproduce on a similar device and Android version, confirm the fix with StrictMode or a system trace, and check the cluster in the next release.
- Senior
- First I check distribution: which release introduced it, which devices and Android versions, and the ANR type. I read the whole trace for lock chains, not just the top frame, and compare with ApplicationExitInfo traces from our own reporting. If the main thread is idle in the trace, the work may have finished just before the dump, so I capture a Perfetto trace while reproducing to see what actually took the time. For a receiver or service ANR I also check startup cost and whether the work should move to WorkManager. Then I verify the cluster declines after the fix ships.
Explain the difference between cold, warm, and hot start in Android.
- Junior
- A cold start happens when the process is not running, so the system creates it and runs Application.onCreate and the Activity from scratch. A warm start recreates the Activity, often in a process that is still alive. A hot start brings an Activity that is still in memory back to the front with onStart and onResume.
- Mid
- Cold start pays for process creation, Application.onCreate, content providers, Activity creation, inflation or composition and the first frame. Warm start skips some of that: the Activity is recreated, possibly from a saved state bundle after the process was killed. Hot start only brings the existing Activity forward, though it may need to redraw if memory was trimmed. I optimise cold start first because improving it usually improves the others.
- Senior
- I measure each type separately with Macrobenchmark's StartupMode.COLD, WARM and HOT and StartupTimingMetric on a real device, and watch Android vitals for slow starts per release. I use Perfetto traces of cold starts to find main-thread work before the first frame: content providers, Application.onCreate, Activity inflation, and class loading. Baseline Profiles help most where code would otherwise run interpreted or JIT-compiled, which is most visible on cold start after install or update.
What is a Baseline Profile and how do you generate and ship one?
- Junior
- A Baseline Profile is a list of classes and methods that Android Runtime compiles ahead of time, so startup and key screens are fast from the first launch. You generate it with the Baseline Profile Gradle plugin and a Macrobenchmark test.
- Mid
- I create a producer test module with the androidx.baselineprofile plugin and write a test with BaselineProfileRule.collect() that starts the app and runs key journeys. Running ./gradlew :app:generateBaselineProfile runs it on a device and writes the rules into the app's generated source folder. The app ships them in the APK as assets/dexopt/baseline.prof. Play delivers the profile with the APK so ART compiles those methods at install time; profileinstaller installs it on first run for non-Play installs.
- Senior
- I set includeInStartupProfile = true for the startup journey, so R8 also uses those rules to place startup code in the primary DEX. Profiles are collected on a non-minified variant and rewritten for the R8 output, so I do not hand-edit them. I run generation as part of the release process on a stable device or a Gradle managed device, and I verify with a Macrobenchmark that compares CompilationMode.None with CompilationMode.Partial(BaselineProfileMode.Require). Libraries can ship their own profiles too, which get merged into the app.
What are TTID and TTFD, and when should you call reportFullyDrawn()?
- Junior
- TTID, time to initial display, is the time until the first frame appears; the system reports it automatically. TTFD, time to full display, is the time until real content is visible; you report it by calling reportFullyDrawn().
- Mid
- Call reportFullyDrawn() once the first screen shows its real content, for example after the list has its data. Calling it at the end of onCreate makes TTFD equal TTID. In Compose I use ReportDrawnWhen with a condition like !isLoading. Macrobenchmark's StartupTimingMetric reports both timeToInitialDisplay and timeToFullDisplay.
- Senior
- When several components load independently, I use fullyDrawnReporter: each one adds a reporter and removes it when ready, and reportFullyDrawn() fires once all are removed. Only the first call counts. I keep an eye on both metrics: TTID shows startup cost, TTFD shows data loading cost, and they need different fixes. I track them in Macrobenchmark on release candidates and watch percentiles, not just the median, because slow devices and slow networks show up in the tail.
How does the App Startup library work and what are its constraints?
- Junior
- The App Startup library (androidx.startup) lets libraries and apps share one ContentProvider for initialisation. You write an Initializer class, register it in the manifest, and it runs at app startup.
- Mid
- Each Initializer<T> has create(context), which returns the initialised object, and dependencies(), which lists Initializers that must run first. InitializationProvider reads the meta-data entries from the merged manifest at startup and runs them in dependency order before Application.onCreate. create() runs on the main thread, so it must be fast.
- Senior
- The main win is replacing many library ContentProviders with one, and making initialisation explicit. For anything not needed before the first frame I make it lazy: remove its meta-data entry with tools:node="remove" and call AppInitializer.getInstance(context).initializeComponent(...) when needed. Because initialisers run before Application.onCreate, a failure there happens before most of my app code runs, so I keep them small and test them. I confirm the effect with a cold-start Macrobenchmark and a Perfetto trace.
What is jank in Android and what are the most common causes?
- Junior
- Jank is when the app does not produce a frame in time for the screen refresh, so the screen stutters. At 60 Hz the budget is about 16.7 ms. Common causes are heavy work on the main thread, like I/O, big layouts or decoding images in onBindViewHolder.
- Mid
- A frame must get through input, animation, measure and layout, draw recording on the main thread, then rendering on the RenderThread and GPU, then composition by SurfaceFlinger, before its deadline. Common app causes are slow binding, deep layouts, Compose recomposing too much, main-thread I/O, and large bitmaps or overdraw on the render side. I measure with JankStats and FrameTimingMetric and diagnose with Perfetto.
- Senior
- Beyond main-thread work I look at blocking: the main thread waiting on a lock, a binder call, or I/O shows as sleeping time inside a long frame. GC work from heavy allocation during scroll adds CPU contention. On 90 and 120 Hz screens the budget shrinks, so I measure against the real refresh rate. In Perfetto I use the Android 12+ frame timeline to see whether the app or the system missed the deadline, then I check the main thread and RenderThread for that frame. In production I use JankStats states to rank screens and actions by jank, so we fix what users hit most.
Explain the Android frame pipeline from vsync to display.
- Junior
- The display sends a vsync signal. Choreographer on the main thread runs input, animation, and layout, then the UI is drawn, the GPU renders it, and SurfaceFlinger puts it on the screen.
- Mid
- Vsync triggers Choreographer#doFrame on the main thread: input, animation, measure and layout (or composition), then draw, which records display lists. The RenderThread syncs those display lists, issues GPU commands and queues the buffer. SurfaceFlinger composites the app's buffer with other layers for the display. Main thread, RenderThread and GPU work can overlap across frames, but each frame still has a deadline.
- Senior
- On devices with variable refresh rates the vsync period changes, so the budget is not fixed. In Perfetto I follow one frame: the Choreographer#doFrame slice on the main thread, the matching DrawFrame slice on the RenderThread, then the Expected and Actual Timeline tracks. If doFrame is long, the problem is main-thread work or blocking. If doFrame is short but DrawFrame is long, I look at render cost: big bitmaps, overdraw, shader compilation. If both are short and the frame is still late, the jank type usually points at the system side or buffer stuffing from earlier late frames.
How do you use Perfetto to diagnose a jank issue?
- Junior
- I record a system trace from Android Studio while reproducing the stutter, open it, and look at the main thread for slices that take longer than the frame budget.
- Mid
- I add trace sections with androidx.tracing around suspect code, build a profileable release build, and capture a trace with Android Studio or adb shell perfetto with the gfx, view, input and sched categories. In ui.perfetto.dev I find my app's process, look at the Actual Timeline for late frames, then zoom into Choreographer#doFrame on the main thread and DrawFrame on the RenderThread for those frames to see which slices are long.
- Senior
- I start from the late frame in the Actual Timeline and its jank type, then check the main thread state during that frame: Running means CPU work in my code (my trace sections tell me which), Sleeping or blocked means a lock, I/O or binder call, and I follow the thread that woke it. I check CPU frequency and scheduling too, because a thread waiting for a CPU core looks different from one doing work. After the fix I compare a new trace and a FrameTimingMetric benchmark, not just how it feels.
What is JankStats and when would you use it instead of a Perfetto trace?
- Junior
- JankStats is an AndroidX library that tells you which frames were janky while users use the app. You use it to measure jank in production; Perfetto is for investigating one case in detail.
- Mid
- You call JankStats.createAndTrack(window, listener), and the listener gets FrameData for each frame with isJank, the frame duration and the current UI states. You enable tracking in onResume and disable it in onPause, and tag states with PerformanceMetricsState, like the screen name or 'scrolling'. It works back to old API levels by using FrameMetrics on API 24+ and OnPreDrawListener before that.
- Senior
- JankStats answers 'where and how often', Perfetto answers 'why'. I aggregate JankStats data per screen and state, sample it to keep overhead and data volume low, and send it to analytics so a regression in one release is visible. When a screen stands out, I reproduce the action, capture a Perfetto trace and fix it, then confirm with a FrameTimingMetric benchmark in CI and with the JankStats numbers in the next release.
What is Doze mode and how does it affect a background sync?
- Junior
- Doze is a power-saving mode that starts when the phone is unplugged, still and has its screen off. It cuts network access and delays background work like WorkManager jobs until a short maintenance window.
- Mid
- In Doze the system suspends network, ignores wake locks, defers alarms (even setExact) and does not run JobScheduler jobs or sync adapters until a maintenance window, and the windows get further apart over time. WorkManager runs on JobScheduler, so a sync simply runs late. Android 7.0 added a lighter Doze phase that applies while moving. You test it with adb shell dumpsys deviceidle force-idle.
- Senior
- I design sync so that running late is fine: the database is the source of truth, the UI shows cached data, and WorkManager catches up in a maintenance window. For something the user must see now, the server sends a high-priority FCM message, which gives the app a short network window, and the app shows a notification. setAndAllowWhileIdle and setExactAndAllowWhileIdle exist but are rate-limited. App Standby buckets add a second layer on top of Doze, so I check behaviour with am set-standby-bucket rare and restricted, not only with force-idle.
How do you schedule periodic background work in a modern Android app?
- Junior
- Use WorkManager with a PeriodicWorkRequest. The minimum interval is 15 minutes, and you can add constraints such as unmetered network or charging.
- Mid
- I build a PeriodicWorkRequestBuilder with Constraints, set backoff with setBackoffCriteria, and enqueue it with enqueueUniquePeriodicWork and ExistingPeriodicWorkPolicy.KEEP so app restarts do not create duplicates. WorkManager persists work across process death and reboot and uses JobScheduler on API 23+. Exact alarms are for user-facing time-critical features, not sync.
- Senior
- I keep all scheduling in one place so periodic work can be audited, and I choose constraints per job: CONNECTED for small syncs, UNMETERED and battery-not-low for large uploads. I avoid setRequiresDeviceIdle for anything the user expects to see, and remember it cannot be combined with backoff criteria. If the product asks for one-minute polling, I push back toward server push with FCM instead of a long-running foreground service, since foreground services need a visible notification and a declared type that fits the use case. I verify with adb shell dumpsys jobscheduler and the Background Task Inspector in Android Studio.
How does OkHttp caching work and when should a response not be cached?
- Junior
- You give OkHttpClient.Builder a Cache with a directory and a maximum size. OkHttp stores responses on disk and can return them without a network call.
- Mid
- The cache follows HTTP caching headers. A response with Cache-Control max-age is served from disk until it expires; a response with an ETag or Last-Modified is revalidated with a conditional request, and a 304 reuses the cached body. Personal or sensitive data should be sent with Cache-Control: no-store. You can see whether a response came from cache through response.cacheResponse and response.networkResponse.
- Senior
- Caching is a contract with the backend, so I agree on headers per endpoint instead of forcing cache behaviour in interceptors. I share one client so the cache and connection pool are shared, and OkHttp uses HTTP/2 to multiplex calls to the same host on one connection. With Retrofit, response.raw().cacheResponse tells me hit or miss, which I log in debug builds. For offline-first screens the HTTP cache is not the source of truth; Room is, and the HTTP cache just makes refreshes cheaper.
How would you investigate a battery drain report?
- Junior
- Check Android vitals in Play Console for wake lock problems, then look at the app on a test device with adb shell dumpsys batterystats.
- Mid
- I reset stats with adb shell dumpsys batterystats --reset, reproduce, then read adb shell dumpsys batterystats --charged with my package name. adb shell dumpsys power shows held wake locks, and adb shell dumpsys jobscheduler shows pending jobs and their constraints. A Perfetto trace or Battery Historian can show when the device woke and why.
- Senior
- I look for one of three patterns: a held lock (a wake lock or a foreground service left running), a retry storm (work that fails and retries too often), or polling that should be push. I correlate the Android vitals spike with the app version that introduced it, check retry and backoff settings, and add debug logging of worker start, end and result. The fix is usually removing work, not tuning it: batch requests, cache responses, and replace timers with WorkManager or FCM.
How do you handle uncaught exceptions in an Android app?
- Junior
- I add a crash reporting SDK like Firebase Crashlytics. It installs an uncaught exception handler that saves the crash and sends it on the next launch. If I need my own handler, I set it with Thread.setDefaultUncaughtExceptionHandler in Application.onCreate.
- Mid
- The default handler is process-wide and covers every thread. A custom handler must save the previous handler first and call it at the end, otherwise Crashlytics and the system never see the crash. I keep the handler minimal, for example a custom key, and I do not call recordException there because Crashlytics already records the fatal crash.
- Senior
- I treat the handler chain as a contract: capture previous, do tiny work in try, call previous in finally, never kill the process or swallow the exception. Order matters: Crashlytics installs its handler at startup, so mine sits in front of it. For anything I cannot catch in-process, such as ANRs, native crashes and low-memory kills, I read ApplicationExitInfo on the next start. I verify the whole path in a minified release build by forcing a crash and checking that Crashlytics shows a fatal issue with readable names.
What is the difference between a fatal crash and a non-fatal in Crashlytics?
- Junior
- A fatal crash is an uncaught exception that ends the app. A non-fatal is an exception I caught and reported with recordException while the app keeps running.
- Mid
- Fatal crashes count toward crash-free users; non-fatals do not. I record non-fatals in catch blocks around risky work such as parsing or file reads, with setCustomKey and log for context. I never report CancellationException, and I do not report expected cases such as no network as errors.
- Senior
- Non-fatals are a signal budget. I record only unexpected states, group them so one root cause makes one issue, and attach the screen or feature as a custom key without personal data. I check that the release smoke test produces one fatal, not a fatal plus a duplicate non-fatal from a handler calling recordException. Rising non-fatals for one feature after a release are an early warning I act on before crashes follow.
Why do production stack traces show names like a.b.c, and how do you fix it?
- Junior
- R8 shortens class and method names in release builds. Crashlytics needs the mapping.txt file from that build to turn them back into real names.
- Mid
- With isMinifyEnabled = true, R8 writes mapping.txt to app/build/outputs/mapping/release/. The Crashlytics Gradle plugin embeds a mapping file ID in the app and uploads that build's mapping automatically, so I make sure the plugin is applied and uploads are not disabled in CI. Play Console reads the mapping from an app bundle by itself.
- Senior
- I make mapping handling part of the release pipeline: the plugin uploads for Crashlytics, CI archives mapping.txt per build, and I can run R8's retrace locally for traces from logcat or other tools. Since the mapping is per build, a hotfix built without the plugin, or a build rerun after upload, gives wrong or missing names, so I check one forced crash per release. I also keep line numbers in traces with -keepattributes SourceFile,LineNumberTable and optionally -renamesourcefileattribute SourceFile.
How does ApplicationExitInfo help with crash analysis?
- Junior
- From Android 11 (API 30) the system records why the app's process ended. On the next launch I read the list and send it to my analytics.
- Mid
- I call ActivityManager.getHistoricalProcessExitReasons(packageName, 0, 0) on a background thread at startup. Each ApplicationExitInfo has a reason such as REASON_CRASH, REASON_ANR, REASON_CRASH_NATIVE or REASON_LOW_MEMORY, a timestamp and a description. It catches deaths my handler never sees.
- Senior
- I record which exits I have already reported, using the timestamp, so each one is sent once. For ANRs, getTraceInputStream() gives the thread dump, which is what I need to find main-thread I/O or lock contention. Low-memory kills are not crashes but tell me the app is losing state in the background, which points to state restoration bugs. This pairs with Play Console's ANR and crash reports to cover cases Crashlytics alone misses.
What does R8 do, and when does it shrink your code?
- Junior
- R8 is the Android compiler that shrinks, optimizes and obfuscates code. It does that when isMinifyEnabled = true is set on a build type, usually release. It also writes mapping.txt so crash traces can be decoded.
- Mid
- Shrinking removes unreachable classes and members, optimization inlines and merges code, and obfuscation renames what is left. isShrinkResources = true removes unused resources too. Since AGP 8.0 R8 runs in full mode by default, which keeps less implicitly, for example default constructors and generic signatures of classes no rule keeps.
- Senior
- I treat R8 as part of the release contract: anything reached by reflection, JNI or name-based serialization needs an explicit, narrow rule, and I verify with a minified build in CI, not only debug. I look at -printusage when something disappears and at -printseeds when a rule is too broad. I make sure mapping.txt per build reaches Play (bundle) and Crashlytics (Gradle plugin), and I keep line numbers with -keepattributes SourceFile,LineNumberTable.
How do you debug a crash that only happens in release?
- Junior
- First I deobfuscate the stack trace. Crashlytics and Play Console do it if they have the mapping file; otherwise I run retrace mapping.txt stacktrace.txt from the Android SDK command-line tools.
- Mid
- The mapping file must come from the exact build that crashed, since it changes every build. Once the trace is readable, I look for ClassNotFoundException, NoSuchMethodException or fields with default values, which usually mean a class or member used by reflection was removed or renamed. I reproduce with a local minified build and add a targeted keep rule.
- Senior
- I tie mapping files to builds in CI (artifact per version code) so a hotfix cannot lose them, and I keep a release-variant test that exercises reflection-heavy paths like JSON parsing and plugin loading. If I need to confirm R8 is the cause quickly, I try android.enableR8.fullMode=false or a broad temporary rule locally, then narrow it to the smallest rule before merging.
What is the difference between -keep, -keepclassmembers and -keepnames?
- Junior
- -keep keeps a class from being removed or renamed, along with the members you list. -keepclassmembers keeps listed members but only if the class is kept anyway. -keepnames stops renaming but still lets R8 remove unused code.
- Mid
- I use -keepclassmembers for serialization DTOs that are already referenced directly, so only their fields need protection. I use -keep with a member list when a class is created by name, for example keep class * implements Plugin with public <init>(). -keepnames suits classes whose names show up in logs or analytics but that are otherwise referenced normally.
- Senior
- Broad rules like -keep class com.example.** { *; } quietly disable shrinking and renaming for a whole package, and in a library consumer file they do that in every app. I review rule files like code, check -printseeds output for what each rule matches, and prefer libraries that ship their own rules or avoid reflection, such as kotlinx.serialization or Moshi codegen.
What is consumer-rules.pro and when do you use it?
- Junior
- It is a keep-rule file in a library module that gets applied to every app that depends on the library, so app developers do not have to write those rules themselves.
- Mid
- A library declares it with consumerProguardFiles("consumer-rules.pro") and AGP packages it in the AAR. The library's own proguard-rules.pro is only used if the library itself is minified and is not passed to consumers. If the library uses reflection, the rule must be in consumer-rules.pro or every minified app breaks.
- Senior
- I treat consumer rules as part of the library's public contract: a change can alter what R8 keeps in every consuming app, so it goes in the changelog. Rules stay narrow and only cover what the library itself needs; global options do not belong there. I test them with a minified sample app in the library's CI that exercises the reflective paths.
Offline-first
What is a single source of truth in an offline-first Android app?
- Junior
- It means the local database, usually Room, is the only place the UI reads data from. The network result is saved into Room, and the UI observes Room with Flow.
- Mid
- The repository exposes Flow reads backed by Room, and network data only updates Room. Because every screen observes the same tables, they stay consistent, and the app shows saved data offline. I also keep separate network, entity and external models so a backend change does not leak into the UI.
- Senior
- The local data source is canonical for reads, the server is the authority for the shared state, and sync reconciles them. That raises the real questions: writes go to Room first with a pending marker, refreshes must not overwrite pending rows, deletions on the server need explicit handling because upsert does not remove rows, and multi-table writes go in a transaction so observers never see half an update. Errors are separate UI state, not a reason to clear the cache.
A refresh succeeds on the network but the database write fails. What happens and how do you handle it?
- Junior
- The UI does not change because it reads from the database. I catch the error and show a message to the user.
- Mid
- Since the UI observes Room, nothing changes on screen, which is correct: the truth did not change. The repository lets the exception reach the ViewModel, which shows an error state, and the next refresh simply tries again because refreshes are idempotent.
- Senior
- A network call and a database write cannot share one transaction, so I make the local write safe to repeat instead. I put all the related writes (rows, deletions, sync metadata) in one Room @Transaction, so a failure leaves the old consistent state. Refresh is idempotent, so a retry, from the user or a WorkManager sync with backoff, converges. Real causes of failed writes are usually constraint violations or a full disk, so I log them rather than retry forever.
Why shouldn't the ViewModel hold business data in its own MutableStateFlow?
- Junior
- Because then the ViewModel and the database can show different data.
- Mid
- It creates a second source of truth. If a worker or another screen updates Room, the ViewModel's copy does not know about it and the screen goes stale. The ViewModel should expose the repository Flow with stateIn.
- Senior
- The ViewModel should own screen state, such as input text, selection or a refresh error, and derive everything else from the repository Flow, often with combine. Holding a copy of business data invites ordering bugs where a late network response or a background sync overwrites a newer value. Deriving state from Room also survives process death, because the data is reloaded from disk.
How do you show cached data immediately and still keep it fresh?
- Junior
- Show the data from Room first, then call the API and save the new data into Room.
- Mid
- The screen collects the Room Flow, which emits the cached rows at once. The ViewModel triggers a refresh; when it writes to Room, the Flow emits again. If the refresh fails, the cached rows stay and I show an offline message.
- Senior
- That is stale-while-revalidate at the app level. I store a fetchedAt time per data type and only refresh when the data is older than its TTL, plus on pull-to-refresh. Long-term freshness can come from WorkManager sync with a network constraint. The UI distinguishes loading with no data, offline with no data and stale data. I test it with a fake DAO and an API fake that fails on demand.
How do you handle a write that the server rejects because the data changed in the meantime?
- Junior
- The server says my copy is out of date, so I download the latest version, combine it with my change, and send it again.
- Mid
- Each row keeps the server version or ETag. The write sends it in If-Match, and the server returns 412 (or 409, depending on the API) if it is stale. The worker fetches the current row, merges field by field against the base copy, saves the result to Room and retries with the new version. Retrying the same request without merging would fail forever.
- Senior
- It is optimistic concurrency with the server as the authority. I keep the base snapshot with each pending edit so I can do a real three-way merge: one-sided changes merge automatically, same-field changes follow a per-field rule or go to the user. New versions only come from the server. Retries are bounded, use WorkManager backoff for transient errors, and carry an idempotency key so a timed-out request is not applied twice. I test it with a fake API that rejects the first write and assert both edits survive.
What is an idempotency key and when is it generated?
- Junior
- It is a unique ID sent with a write so the server can ignore a duplicate. I create a UUID when the user makes the change.
- Mid
- It is a client-generated UUID created when the write is queued and stored with the pending row, so every retry sends the same key. It matters when a request times out after the server already processed it; the retry is recognised and the server returns the original result. Generating it at send time would give each retry a new key.
- Senior
- It makes retries safe at the server: the server stores processed keys, usually with a unique constraint and an expiry, and returns the stored response for a repeat. Often the simplest version is a client-generated ID for the record itself, so creating the same record twice is naturally a no-op. It solves duplicates, not conflicts; a stale edit still needs version checks and merging.
When would you use last write wins, field-level merge or server-decides?
- Junior
- Last write wins keeps the newest save. Field merge keeps both changes if they touched different fields. Server-decides lets the server apply its rules.
- Mid
- Last write wins suits data with one owner or low value, like settings or read markers, ideally ordered by the server. Field-level merge suits records with independent fields like a note's title and body. Server-decides is for business rules such as approvals or stock. The pitfall is assuming fields are independent when they are not, like a date range.
- Senior
- I choose per field, not per entity. One record can use last write wins for a favourite flag, three-way merge for text fields and server-decides for status. For operations like counters I send intents (add 2) instead of values so concurrent changes add up. I log which rule ran and what was discarded, because silent data loss is invisible otherwise, and I test with generated edit sequences from two simulated devices.
What is the difference between pull-based and push-based sync?
- Junior
- With pull, the app asks the server for data when it needs it. With push, the server tells the app when data has changed.
- Mid
- Pull fetches data just before a screen needs it, like Paging's RemoteMediator. It is simple but refetches unchanged data and leaves screens empty after long offline periods. Push keeps a local replica: the app loads a baseline, then the server sends a notification such as an FCM message when data is stale, and the app fetches only the changes.
- Senior
- Push needs backend support: change tokens or cursors for incremental fetches, tombstones for deletes, and versions for conflicts. It lets the app work offline for long periods with little data use. Many apps go hybrid, pulling a fast-changing feed and pushing user-owned data. Either way the fetch runs through the repository and writes to Room, usually in a WorkManager job with a network constraint, and must not overwrite pending local edits.
How would you implement offline writes in an Android app?
- Junior
- Save the change in Room first with a pending status so the UI shows it right away, then use WorkManager to send it to the server when there is a network connection.
- Mid
- The repository writes to Room with a PENDING state and enqueues a CoroutineWorker as unique work with a CONNECTED network constraint and exponential backoff. The worker uploads pending rows, marks them SYNCED, and returns Result.retry() on IOException so the rows stay queued. I generate IDs on the device so a retried upload cannot create a duplicate.
- Senior
- I separate transient from permanent failures: IOException, 5xx and 429 retry with backoff, validation errors mark one row FAILED and show it in the UI, and 401 waits for sign-in. Uploads are idempotent through client IDs or an idempotency key, rows edited during an upload stay pending through a local revision check, and the worker drains in batches. Stale-write conflicts are handled with versions on the server. I test the worker with TestListenableWorkerBuilder and a fake API that times out after saving.
Which ExistingWorkPolicy would you use for a write-sync worker, and why?
- Junior
- A unique work policy so that only one sync runs at a time, for example KEEP or APPEND_OR_REPLACE.
- Mid
- REPLACE cancels the running sync on every write, which can cut an upload off. KEEP ignores new requests while sync is unfinished, which is fine if the worker keeps reading until the queue is empty. APPEND_OR_REPLACE adds a run after the current one, so a write made during the sync is always uploaded.
- Senior
- The worker reads its work from Room, not from Data, so I need the guarantee that a run starts after the last write, not the request itself. APPEND_OR_REPLACE gives that, and unlike APPEND it does not inherit a failed or cancelled parent. KEEP is what Now in Android uses for its start-up sync and is fine with a drain loop. I would never use REPLACE for uploads, and periodic sync uses enqueueUniquePeriodicWork with its own ExistingPeriodicWorkPolicy.
How do you prevent duplicate writes when WorkManager retries?
- Junior
- Send a unique ID with each write so the server can tell it already received it.
- Mid
- The duplicate happens when a request times out after the server saved it. I create the record's ID on the device, store it in Room, and use it in an idempotent PUT, or send it as an idempotency key on a POST. Every retry carries the same ID, so the server ignores repeats.
- Senior
- The ID must exist before the first attempt, so it is created with the local write, never at send time. The server enforces it with a unique constraint and returns the original response for a repeat. That makes retries safe, but it does not resolve conflicts between devices; for that the request also carries the version the edit was based on.
What happens to WorkManager work when the app process is killed or the device reboots?
- Junior
- WorkManager saves the work, so it still runs later even if the app is closed or the phone restarts.
- Mid
- WorkManager stores work requests in its own database. After process death or a reboot it reschedules unfinished work, and the worker runs once its constraints are met. If the user stays offline, the work simply stays ENQUEUED.
- Senior
- Persistence is why WorkManager suits write queues, but a worker can still be stopped mid-run when constraints are lost or the system stops it, so doWork must be safe to rerun from the start: idempotent uploads, state in Room rather than in memory, and per-row progress. Force-stopping the app from Settings cancels its scheduled work until the app is launched again, so I also enqueue the sync on app start. I check behaviour with WorkInfo states from getWorkInfosForUniqueWorkFlow.
Security
How does the Android Keystore protect a key from the application?
- Junior
- The key is created inside the Keystore and the app only gets a handle to it. The app asks the Keystore to encrypt or decrypt, but it never sees the raw key bytes.
- Mid
- Keys are generated with KeyGenParameterSpec and stored by the Keystore system service for the app's UID. On devices with a TEE or StrongBox, key material stays in secure hardware and operations such as Cipher.doFinal run there. You can also restrict a key: purposes, block modes, user authentication, unlocked-device-only.
- Senior
- The guarantee is non-extraction, not secrecy of the data: anyone who can run code as your app can still ask the Keystore to decrypt. So I combine it with user authentication for high-value keys, and I check KeyInfo.securityLevel on API 31+ when the threat model needs hardware backing, because some devices fall back to software. For stronger claims to a server, Key Attestation lets the backend verify that a key was created in secure hardware on a genuine device.
When does a Keystore key throw KeyPermanentlyInvalidatedException?
- Junior
- When something about the device's security changes, such as the lock screen. The app should catch it and create a new key.
- Mid
- For keys created with setUserAuthenticationRequired(true), the key is invalidated if the secure lock screen is disabled or reset. Keys that require biometric authentication are also invalidated when a new biometric is enrolled, unless setInvalidatedByBiometricEnrollment(false) was set. Cipher.init throws the exception, and the data encrypted with that key is lost.
- Senior
- I design for it up front: the encrypted value must be something the app can get again, such as a refresh token that a fresh sign-in replaces. Recovery is catch at Cipher.init, delete the alias, clear the ciphertext, re-authenticate, create a new key. I keep the default enrollment invalidation for banking-style flows, because otherwise someone who knows the PIN can enroll their own finger and unlock the secret.
A codebase stores a JWT in EncryptedSharedPreferences. What do you change?
- Junior
- EncryptedSharedPreferences is deprecated, so I would move to a supported option such as Tink or a Keystore key with DataStore.
- Mid
- I would migrate to Tink's AndroidKeysetManager, which keeps its keyset encrypted with a Keystore master key, and store the Aead ciphertext in DataStore. The migration reads the old value once, writes it through the new path, and deletes the old file.
- Senior
- Besides the library, I look at the token itself. A long-lived bearer token is valuable to anyone who can run code as the app, so I keep access tokens short-lived, store only the refresh token encrypted at rest, and make the server rotate refresh tokens and detect reuse. For high-risk actions I bind the key to user authentication or use a server-side step-up check, rather than relying only on local encryption.
How do you keep a third-party API key out of attackers' hands?
- Junior
- Do not put it in the app. Anything in the APK can be extracted.
- Mid
- Keep the key on a backend and have the app call that backend with the user's token. If a key must ship in the app, as some SDK keys do, restrict it in the provider's console to your package name and signing certificate and set quotas.
- Senior
- I treat any value in the APK as public and design around that: backend proxy for paid or privileged APIs, per-user rate limits, and Play Integrity verdicts checked on the server to make automated abuse harder. Obfuscation or native code only slows extraction. I also add a CI check that scans the release artifact for known key patterns so a regression is caught before release.
What is certificate pinning and what is the main operational risk?
- Junior
- Pinning stores a hash of the server's public key in the app and checks it during the TLS handshake. The main risk is that if the server's key changes and the app has only one pin, every user's app stops connecting.
- Mid
- The pin is the base64 SHA-256 of a certificate's SubjectPublicKeyInfo, set in NSC or in OkHttp's CertificatePinner. It survives renewals that keep the same key, but a new key or a switch to another CA breaks it, and OkHttp throws SSLPeerUnverifiedException. Mitigation: a backup pin, an expiration on the NSC pin-set, and coordination with whoever manages the server certificates.
- Senior
- Pinning protects against mis-issued certificates from trusted CAs, but it moves certificate management into your release cycle: a server change can now break old app versions you cannot update. I choose what to pin deliberately: our own leaf key gives the strongest protection and the most outage risk, a CA key is more forgiving. I always ship a backup, prefer NSC so the pins expire, monitor the live chain in CI, and for many apps I recommend not pinning at all and relying on Certificate Transparency and normal validation.
How do you configure Network Security Configuration in an Android app?
- Junior
- Create res/xml/network_security_config.xml and reference it with android:networkSecurityConfig on the application tag. Inside you use elements such as domain-config, pin-set and trust-anchors.
- Mid
- base-config sets defaults for all connections, and domain-config overrides them for specific hosts. For apps targeting API 28+, cleartextTrafficPermitted defaults to false, so you only allow HTTP for hosts that need it. pin-set holds pins with an optional expiration, and debug-overrides adds trust only for debuggable builds. Without the manifest attribute the file is ignored.
- Senior
- There is one NSC file per app, set on the application element, so in a multi-module project I check the merged manifest to confirm which file wins. I keep release rules strict in src/main and put local-server exceptions in a debug source set. I verify that every HTTP stack in the app, including SDKs, goes through the platform trust manager, because NSC does not cover clients with their own TLS implementation.
How do you test pinned connections in a debug build without weakening release?
- Junior
- Add a debug-overrides block that trusts user-installed certificates. That lets a proxy like Charles work in debug builds, and release builds ignore it.
- Mid
- debug-overrides is applied only when the app is debuggable, so one NSC file can serve both builds. The mistake to avoid is trusting user CAs in base-config, which would also apply to release. Note that OkHttp's CertificatePinner still checks pins in debug, so a proxy certificate fails unless you skip the pinner in debug builds.
- Senior
- I keep the pinner out of the debug client through DI, rely on debug-overrides for proxy testing, and test the release configuration explicitly: an instrumented test against a local TLS server with a known certificate, one case with a matching pin and one with a wrong pin that must fail with SSLPeerUnverifiedException. Android Lint's InsecureBaseConfiguration check catches the most common release mistake.
When would you use OkHttp CertificatePinner instead of NSC, or both?
- Junior
- NSC applies to the whole app's connections. CertificatePinner is set on one OkHttpClient. Retrofit apps that use OkHttp can use either.
- Mid
- NSC covers every connection that uses the platform trust manager, including HttpsURLConnection and other libraries, and supports expiry. CertificatePinner is code: easy to unit test and to enable per client, but it has no expiry and only covers that client.
- Senior
- I default to NSC because of coverage and expiration, which limits the damage from forgotten old builds. I add CertificatePinner when I need behaviour NSC does not offer, for example skipping pinning in a debug DI graph, or when part of the app uses a TLS stack that ignores NSC. In either case pins live in the APK, so changing them needs a release; I plan key changes with the server team around that.
What is the difference between BiometricPrompt with and without a CryptoObject?
- Junior
- Without a CryptoObject the app just gets a success callback. With a CryptoObject the biometric unlocks a cryptographic key, which is stronger.
- Mid
- With a CryptoObject you pass a Cipher, Signature or Mac initialised with a Keystore key that requires authentication. After success, that object can be used for one operation, for example decrypting a stored token. Without it, success is only a callback and anything gated by it can be bypassed if the callback is faked.
- Senior
- The key requires authentication inside the Keystore, so the guarantee comes from secure hardware, not from my code path. I use it whenever the result protects data or proves something to the server, for example signing a server challenge with a private key. That requires BIOMETRIC_STRONG, optionally with DEVICE_CREDENTIAL on API 30+, and handling key invalidation when a new biometric is enrolled. Plain callbacks are fine only for convenience features where a bypass reveals nothing sensitive.
Explain the role of PKCE in OAuth 2.0 on mobile.
- Junior
- PKCE stands for Proof Key for Code Exchange. It makes the authorization code flow safe for mobile apps that cannot keep a client secret.
- Mid
- The app generates a random code_verifier, sends its SHA-256 hash as the code_challenge in the authorization request, and sends the verifier itself when exchanging the code for tokens. The server checks they match, so an intercepted code is useless without the verifier.
- Senior
- On Android another app can register the same custom-scheme redirect and receive the code, so PKCE is what makes a public client safe. I use AppAuth so PKCE, state and nonce are handled correctly, open the login page in a Custom Tab, never ship a client secret, and prefer a verified https App Link as the redirect so the code goes only to my app.
What does Credential Manager do, and what does it not do?
- Junior
- It is a Jetpack API that lets users sign in with passkeys, saved passwords or their Google account from one system sheet.
- Mid
- You call getCredential with options such as GetPasswordOption, GetPublicKeyCredentialOption and GetGoogleIdOption. The result is a PasswordCredential, a PublicKeyCredential with a WebAuthn response, or a Google ID token credential. It replaces the older Smart Lock for Passwords and Google Sign-In APIs.
- Senior
- It is a client-side credential picker, not an identity provider and not a session system. My backend still issues the passkey challenge, verifies the assertion or the ID token's signature and audience, and issues its own session tokens. Generic OAuth with third-party providers still goes through AppAuth. I also handle the no-credentials and cancellation exceptions so the UI falls back to other sign-in options.
How would you design sign-in and biometric unlock for a banking app?
- Junior
- Let the user sign in with a passkey or password, then offer fingerprint unlock for later launches.
- Mid
- Sign-in with Credential Manager (passkeys first) or AppAuth for an external provider. Store a refresh token encrypted with a Keystore key that requires BIOMETRIC_STRONG authentication, and decrypt it through BiometricPrompt with a CryptoObject on each launch.
- Senior
- I keep access tokens short-lived and have the server rotate refresh tokens and detect reuse. For high-value actions such as transfers, I generate a Keystore key pair that requires authentication, register its public key with the server, and sign a server challenge through BiometricPrompt, so the server verifies a fresh signature instead of trusting the app. Key invalidation, lockout errors and devices without strong biometrics fall back to full sign-in, and the server can check Play Integrity verdicts before issuing tokens.
What is the difference between a deep link and a verified App Link?
- Junior
- A deep link is any URI that opens a screen in the app, and other apps can register the same one. A verified App Link is an https link where the website proves the app owns the domain, so it opens only that app.
- Mid
- Verification uses android:autoVerify="true" on an https VIEW/BROWSABLE intent filter and an assetlinks.json file at /.well-known/ on the domain with the package name and signing certificate fingerprint. Since Android 12, unverified web links open in the browser unless the user approves the app for that domain.
- Senior
- I check verification with pm get-app-links on a real build signed by the Play app signing key, because using the upload key fingerprint is the most common failure. Verification is per domain on Android 12+, so I list every host explicitly. A verified link still carries attacker-controlled data, so the handler validates scheme, host and path exactly as it would for a plain deep link.
How do you prevent intent redirection?
- Junior
- Do not pass an Intent you received from another app to startActivity. Build a new Intent with a fixed target.
- Mid
- Intent redirection happens when an exported component takes a nested Intent or a URI from extras and launches it. Because the launch comes from my app, it can reach non-exported components and FileProvider grants. I never launch caller-supplied intents; links carry a route name that I map to explicit destinations.
- Senior
- I keep exported components to a minimum and treat each one as an API with input validation. I enable StrictMode detectUnsafeIntentLaunch in debug builds to catch launches of intents that came from outside, review every startActivity or sendBroadcast whose Intent comes from getParcelableExtra, and add tests that feed crafted nested intents. Google Play's security checks also look for this pattern.
What changed for PendingIntent in recent Android versions?
- Junior
- From Android 12 you must say whether a PendingIntent is mutable or immutable with FLAG_IMMUTABLE or FLAG_MUTABLE.
- Mid
- Apps targeting API 31+ get an IllegalArgumentException if neither flag is set. FLAG_IMMUTABLE should be the default; FLAG_MUTABLE is for cases such as inline reply or bubbles where the system must fill in data. Apps targeting API 34+ also cannot create a mutable PendingIntent around an implicit Intent.
- Senior
- A PendingIntent lets another app act with my app's identity, so I make the base Intent explicit and immutable wherever possible. When mutability is required I still set an explicit component so only the intended fields can be filled. I audit every PendingIntent.getActivity, getService and getBroadcast call, especially ones handed to SDKs or notifications.
How do you validate an intent received by an exported Activity?
- Junior
- Check the URI before using it and only read the values you expect.
- Mid
- Check scheme and host against an allow-list, check that the path has the expected shape, and validate each value with a strict pattern and length. Ignore extras the link contract does not define, and start internal screens with new explicit intents.
- Senior
- I write the link contract down (routes and parameter formats) and implement it as a pure parser that I can unit test with crafted inputs: wrong scheme, wrong host, extra path segments, oversized values, nested intents. I do not use getCallingPackage as an authorisation check because it is null unless the Activity was started for a result. For components only my own apps should call, I use a signature-level permission.
Delivery
How do you make a Gradle build fast in CI?
- Junior
- Cache Gradle's downloaded dependencies and wrapper between runs so each job does not download them again. In GitHub Actions the gradle/actions/setup-gradle action does that for you.
- Mid
- Besides the dependency cache, turn on the Gradle build cache (org.gradle.caching=true) so tasks whose inputs did not change are restored instead of re-run, and the configuration cache (org.gradle.configuration-cache=true) so the configuration phase is skipped when build scripts did not change. Run only the tasks a pull request needs, for example lintDebug and testDebugUnitTest rather than a full build of every variant.
- Senior
- A remote build cache (for example Develocity or a self-hosted cache node) lets CI and laptops share task outputs; usually only CI writes to it. You measure instead of guessing: a Build Scan shows which tasks were cache misses and why, often an absolute path or timestamp leaking into task inputs. You also split work across jobs (checks on pull requests, signed release builds only on main) and watch cache size, since setup-gradle saves from the default branch and other branches read it.
What is Play App Signing and why does it matter for CI?
- Junior
- Google keeps the app signing key that users' devices trust. You sign the bundle with a separate upload key before uploading. So the most important key is never on a laptop or a CI runner.
- Mid
- CI stores the upload keystore as a base64 secret and its passwords as separate secrets, decodes the keystore into the runner's temp directory and lets the signing config read the values from environment variables. Play checks the upload signature, then signs the generated APKs with the app signing key. If the upload key leaks, it can be reset without users noticing.
- Senior
- The trade-off is that Google holds the app signing key, so anything that needs it, such as APKs you distribute outside Play, must use APKs Play generates or a separate setup. The upload key reset is requested by the account owner in Play Console with a new upload certificate, and the app signing key stays the same, so installed apps keep updating. In review you check that the release job alone can read the signing secrets (a protected GitHub environment with reviewers), that pull requests from forks never get them, and that the Play App Signing page shows both certificates so you can register their SHA fingerprints with APIs such as Maps or Firebase.
Describe a release pipeline from merge to production.
- Junior
- On merge to main, CI runs lint and unit tests, builds a signed .aab and uploads it to the internal track. After testing, the build is promoted to production.
- Mid
- The same artifact is promoted through tracks, for example internal to closed to production, so testers and users get exactly what was tested. In production you start a staged rollout at a small percentage and watch Android vitals and crash reports before increasing it. The version code is stamped by CI so every upload is new.
- Senior
- You add a human approval gate (a protected environment) before production and keep promotion as a separate step from upload. Promotion uses the Play Developer API through Gradle Play Publisher (promoteArtifact with a user fraction) or fastlane supply. You plan the way out too: halting stops new installs but does not roll back users who already updated, so the fix is a new build with a higher version code. You verify by checking that the pipeline never rebuilds between tracks and that the rollout percentage is set explicitly, not left at a full release.
How do you handle secrets in a CI pipeline for Android?
- Junior
- Store the upload keystore, its passwords and the Play service-account JSON in the CI secret store, such as GitHub Actions secrets. Pass them to steps as environment variables. Never commit them.
- Mid
- Binary files like the keystore are stored base64-encoded and decoded into a temp directory at run time. Gradle reads passwords from environment variables, and Gradle Play Publisher reads the JSON from ANDROID_PUBLISHER_CREDENTIALS. GitHub masks secret values in logs, but not transformed values, so you never echo them.
- Senior
- You scope secrets to the job that needs them: the check job gets none, the release job gets signing and Play secrets through a protected environment. Pull requests from forks do not receive secrets, which is why release steps run only on main. The Play service account gets only the permissions it needs in Play Console. You add a secret scanner such as gitleaks to pull requests and rotate credentials after any leak, using the upload key reset for the keystore.
Explain Play App Signing and why it matters.
- Junior
- Google keeps the key that signs the APKs users install. I sign my uploads with a separate upload key. Play checks my upload key, then signs the APKs it delivers with the app signing key.
- Mid
- There are two keys. The upload key is mine, stored in CI secrets, and only proves an upload came from my team. The app signing key is held by Google and is the identity installed apps trust for updates. If the upload key is lost or leaked, the account owner requests an upload key reset in Play Console and uploads continue; nothing changes for users.
- Senior
- The trade-off is that Google holds the app signing key, so you plan for things that depend on it: register the app signing certificate's SHA fingerprints (from the Play App Signing page) with services such as Google Sign-In, Maps or Firebase, not just the upload certificate. Distribution outside Play needs APKs that Play generates or a separate signing plan. In a codebase review you check that signingConfigs read from environment variables, that only the release CI job can read the keystore secrets, and that there is a documented reset runbook.
What is an Android App Bundle and when is it required?
- Junior
- An Android App Bundle is an .aab file built with ./gradlew bundleRelease. It is the upload format for Google Play. Play turns it into the right APKs for each device.
- Mid
- It is required for new apps on Google Play. The bundle has all code and resources, and Play generates split APKs per device configuration, such as screen density, CPU architecture and language, so users download less. A common mistake is running assembleRelease, which produces APKs, instead of bundleRelease.
- Senior
- Because you no longer ship the exact APK users install, you test what Play will generate: bundletool build-apks with your upload key, or internal app sharing. You can control splitting in the bundle block of build.gradle.kts, for example turning off language splits when users switch language in the app. Bundles also enable Play Feature Delivery and Play Asset Delivery. Because Play signs the generated APKs, bundles require Play App Signing.
Walk through a release from internal testing to production.
- Junior
- Upload the .aab to the internal testing track and test it. Then promote the release to closed or open testing for more testers, and finally to production.
- Mid
- Promotion moves the same release, with the same versionCode, so users get exactly what testers used. Internal testing is the quickest to reach testers; closed, open and production releases are reviewed by Google, so you allow time. In production you set a rollout percentage instead of releasing to everyone.
- Senior
- I automate it: CI uploads to internal with Gradle Play Publisher or fastlane supply, and promotion to production is a separate, approved step with an explicit user fraction. During the rollout I watch Android vitals and crash reporting and either increase, halt or resume. Halting does not roll anyone back, so the rollback plan is a fixed build with a higher versionCode through the same tracks. I keep a runbook for the halt decision and who can make it.
How do flexible and immediate in-app updates differ?
- Junior
- A flexible update downloads in the background while the user keeps using the app, and installs when the app restarts. An immediate update shows a full-screen Play screen and the user waits until the update is installed.
- Mid
- Both use AppUpdateManager. You check appUpdateInfo for UPDATE_AVAILABLE and isUpdateTypeAllowed, then call startUpdateFlowForResult with an ActivityResultLauncher and AppUpdateOptions.newBuilder(AppUpdateType.FLEXIBLE or IMMEDIATE). For flexible you listen with InstallStateUpdatedListener and call completeUpdate() when the status is DOWNLOADED.
- Senior
- The user can still cancel either flow, and the launcher gets RESULT_CANCELED, so the app decides what happens next; for a required update it explains why and asks again. You choose the type from updatePriority (set per release through the Play Developer API) and clientVersionStalenessDays. In onResume you check for a downloaded flexible update and for an immediate update stuck in DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS, which you resume. Only users on a lower versionCode who are eligible for the new release are offered it.
What is the difference between a staged rollout and an in-app update?
- Junior
- A staged rollout releases a new version to a percentage of users on Google Play. An in-app update is a prompt inside the app, from the Play In-App Updates API, that asks users on an old version to update.
- Mid
- A staged rollout is server-side: Play decides which users are eligible for the new version, and you control it in Play Console or the Play Developer API. In-app updates are client-side: AppUpdateManager checks whether an update is available to this user and starts a flexible or immediate flow.
- Senior
- They combine: the in-app update API only offers a version Play would give that user, so during a 5% rollout most users see no update. That keeps the risk control in the rollout. For a critical fix I would set a high inAppUpdatePriority on the release through the Play Developer API so the app chooses the immediate flow, and still roll it out in stages because the fix itself could be broken.
How would you handle a critical security issue that needs users to update quickly?
- Junior
- Release a fixed version and use the IMMEDIATE in-app update type so users are asked to update before they continue.
- Mid
- Ship the fix with a higher versionCode, set inAppUpdatePriority to a high value when creating the release, and in the app use updatePriority() to start the immediate flow. Check for updates on every app start and resume interrupted immediate updates in onResume.
- Senior
- In-app updates only reach users of Play builds on supported devices, and users can cancel, so for a true minimum version you add a server-side check: the backend or Remote Config says which versionCode is the minimum, and the app blocks with an explanation and an update button if it is below. I would also consider whether the server can stop the exploit for old clients. The rollout can move faster than usual, but still in stages while watching vitals.
A 10% staged rollout shows a high crash rate. What do you do?
- Junior
- Halt the rollout in Play Console and fix the bug.
- Mid
- Halt the rollout so the remaining users do not get it. Find the crash in Android vitals or Crashlytics, filtered by the new versionCode, fix it and ship a new release with a higher versionCode.
- Senior
- Halting freezes the damage but does not roll anyone back, so I look at how many users are on the bad version and whether a server-side flag can turn off the broken feature for them right away. The fix goes through internal testing, then a new staged rollout from a low percentage, possibly with a high in-app update priority so affected users move off the bad build. Afterwards I check why pre-release testing missed it, for example a missing device or API level in the test matrix.
Why might a flexible update never get installed?
- Junior
- The update downloads, but the app never asks the user to restart, so the old version keeps running.
- Mid
- Play does not restart the app for a flexible update. The app must listen for InstallStatus.DOWNLOADED and call completeUpdate(), usually from a snackbar action. If the user leaves before the prompt, the app must check installStatus() in onResume and prompt again.
- Senior
- Other causes: the listener is registered after the download already finished, or unregistered too early when the screen that registered it is destroyed, so the app checks the state from appUpdateInfo on resume instead of relying only on the listener. The download can also fail, which shows up as InstallStatus.FAILED with an installErrorCode. I cover the flow with FakeAppUpdateManager in unit tests and with internal app sharing on a real device.
What is the difference between versionCode and versionName, and what happens if you get versionCode wrong?
- Junior
- versionCode is a positive integer that tells Android and Google Play which build is newer. versionName is the text users see, like 2.4.1. If you upload a versionCode that was already used, Play rejects the upload.
- Mid
- Version codes are unique per app across all tracks; promotion moves the same build with the same code. If a new build has a lower code than what users have installed, those users never get it, because Android blocks downgrades. versionName has no format rules and is never compared, so '2.10.0' versus '2.9.0' is meaningless to the system.
- Senior
- I have CI stamp versionCode from one increasing counter and keep versionName in one property, with a tag per release so crash reports map back to a commit. A pre-upload check reads the highest code on production through the Play Developer API (edits.tracks) and fails if the new one is not higher. I also keep testing tracks above production, because users eligible for several tracks get the highest versionCode available to them. If you derive the code from the semantic version, leave room for each part and stay under Play's maximum of 2100000000.
How do you manage versions across a multi-module Android project?
- Junior
- versionCode and versionName belong to the app module's defaultConfig. Dependency versions go in one place, the Gradle version catalog at gradle/libs.versions.toml.
- Mid
- Library modules inside the same build do not need their own version numbers; they are built together with the app. Third-party versions are referenced through catalog aliases, such as libs.androidx.core.ktx, so every module uses the same one. The pitfall is a hardcoded version string in one module that bypasses the catalog.
- Senior
- Modules published separately, for example to an internal Maven repository for several apps, follow semantic versioning and run a binary compatibility check so a breaking change forces a major bump. Gradle picks the highest requested version in a conflict, so a transitive upgrade can break code compiled against an older version; I review the dependency report or use dependency locking for releases. Strict versions or constraints are the tool when you must hold a version, with a comment saying why.
Release branches versus trunk-based development: which do you choose and why?
- Junior
- Release branches freeze a release while work continues on main. Trunk-based development means everyone merges small changes to main and releases are tagged from main.
- Mid
- Trunk-based development keeps one line of history and one versionCode counter, and relies on feature flags to hide unfinished work. Release branches give a stable place to fix bugs before a release, but each fix must be merged back to main, and each branch needs its own versionCode range.
- Senior
- For a team releasing often, I prefer trunk-based with feature flags and, if needed, a short-lived stabilisation branch cut from main per release. Fixes land on main first and are cherry-picked, so nothing is lost. CI stamps versionCode for every build, so branches cannot collide. Long-lived release branches make sense when several versions are supported at once, such as an enterprise app with pinned customers, and then I assign version code ranges per branch and still keep testing tracks above production.
How does versionCode interact with Play tracks, staged rollouts and in-app updates?
- Junior
- Each track can hold a different build, each with its own versionCode. A staged rollout sends one build to a percentage of production users.
- Mid
- Promoting from internal to production keeps the same versionCode because it is the same build. A fix for a halted rollout needs a new build with a higher versionCode, because users who already updated cannot be moved back. In-app updates are offered only when a higher versionCode is available to that user.
- Senior
- Users eligible for several tracks, such as testers who also have production, get the highest versionCode available to them, so testing builds must stay above production or testers silently fall back to production. During a staged rollout, only users in the rollout percentage see the update, including through the in-app update API. Starting a new production release usually replaces the in-progress rollout; tools like Gradle Play Publisher halt it by default unless told to keep it. I check the codes on each track before promoting.
Advanced testing
Describe the Android test pyramid and how you would apply it to a new feature.
- Junior
- The pyramid has many unit tests at the bottom, fewer integration tests in the middle, and a few end-to-end tests at the top. For a new feature I would write unit tests for the ViewModel and use cases, an integration test for the repository with a fake or in-memory database, and one end-to-end test for the main user flow.
- Mid
- I split the feature by what each test needs. Pure logic (use cases, formatters, ViewModels with fakes) gets local JUnit tests with runTest. Code that touches Android classes, like a Room DAO, gets Robolectric tests or a small instrumented test. The main flow gets one Compose or Espresso test on a device. For DI wiring I use Hilt testing with @TestInstallIn to replace the data module with fakes.
- Senior
- I think in terms of feedback speed and confidence. Local tests give fast, precise feedback and run on every change; device tests are slower, so I keep a small smoke set on pull requests and run the full instrumented suite after merge or on a schedule. I watch the balance over time, because teams drift toward end-to-end tests when logic leaks into the UI layer, and the real fix is moving logic into testable classes. For instrumented tests in CI I use Gradle Managed Devices so the device definition is in the build, not on someone's laptop.
When would you choose Robolectric over a real instrumented test?
- Junior
- Robolectric runs on the JVM, so it is faster than an instrumented test that needs an emulator. I use it for code that needs Android classes, and use instrumented tests when I need a real device.
- Mid
- Robolectric gives a simulated Android framework on the JVM, so tests that use Context, resources, Room or even Compose UI run without an emulator. I choose an instrumented test when I need real hardware or sensors, real rendering, system UI or other apps, or behaviour Robolectric does not simulate faithfully.
- Senior
- The trade-off is fidelity versus speed. Robolectric is a simulation: the framework code runs, but there is no real GPU, real system services or real device quirks. I use it for data-layer and screen-level tests with fakes, and reserve instrumented tests for flows where the real device matters. Robolectric runs against the targetSdk by default, and I add @Config(sdk = [...]) when I need to cover other API levels. Plain Kotlin logic does not need Robolectric at all.
How do you set up a Hilt test that replaces a repository with a fake?
- Junior
- I add @HiltAndroidTest to the test class, add a HiltAndroidRule as a rule, and call hiltRule.inject() before the test. Then I replace the production module with a test module that binds the fake.
- Mid
- If every test should use the fake, I put a module in the test source set with @TestInstallIn(components = [SingletonComponent::class], replaces = [DataModule::class]) that binds the fake. If only one class needs it, I use @UninstallModules on that class with a nested @Module, or @BindValue on a field. Under Robolectric I add @Config(application = HiltTestApplication::class).
- Senior
- I prefer @TestInstallIn for shared fakes, because @UninstallModules makes Hilt generate a separate component for that test class, which adds build time across a big suite. I mark the fake @Singleton so the instance I inject into the test is the same one the code under test receives, then seed it and assert on outcomes. Each test gets a new Hilt graph, so a singleton fake does not leak between tests. And for pure use-case tests I skip Hilt and pass the fake to the constructor.
A CI end-to-end test is flaky. Walk me through your diagnosis.
- Junior
- I run the test many times to see how often it fails. Then I check whether it uses a real network call, depends on timing or animations, and replace those with fakes or proper waiting instead of sleeps.
- Mid
- I look at the failure pattern in the CI logs: same step or random? Common causes are animations, real network calls, wall-clock time, async work the framework cannot see, and state left by a previous test. Fixes are disabling animations, fakes for the network, an IdlingResource or waitUntil for async work, and Android Test Orchestrator with clearPackageData for leaked state.
- Senior
- I categorise the flake as timing, state, or environment. Timing: replace Thread.sleep with an IdlingResource or a waitUntil condition. State: find singletons or persisted data that leak between tests, and use the orchestrator with clearPackageData. Environment: device locale, time zone, animations, or emulator differences, which Gradle Managed Devices and animationsDisabled help control. I also check whether the test covers too much; often half of it belongs in a faster test. A retry can keep CI usable while I fix the cause, but I track retried tests so they do not become permanent.
When do you choose a fake over a mock in Android testing?
- Junior
- A fake is a real implementation with simplified I/O, like an in-memory map instead of a database. A mock is a stub that returns canned values and can verify calls. You use a fake when you want to test real logic and a mock when you want to test interactions.
- Mid
- Google's guide on test doubles prefers fakes in most cases, especially for repositories, because tests then check outcomes against something that behaves like the real thing. Mocks fit when the interaction is the point, like an analytics call, or when a dependency such as a third-party SDK is hard to fake. The common pitfall is mocking a repository and only testing the paths you remembered to stub.
- Senior
- The trade-off is that fakes can drift from the real implementation, so I run the same contract tests against the fake and the real class (for example the real Room DAO with an in-memory database), which keeps them in step. Fakes are written once and shared through a test-fixtures module, so they also cut per-test setup compared with re-stubbing mocks everywhere. Mocks stay for interactions that have no observable outcome, and I avoid verifying internal call order because it ties tests to implementation details.
What is the difference between mockk and spyk in MockK?
- Junior
- mockk creates a completely empty object with no real behaviour. spyk wraps a real object and records calls while delegating to the real implementation. You pick spyk when you need the real logic but also want to assert that a method was called.
- Mid
- With a plain mockk, any call you did not stub throws a MockKException, unless you create it with relaxed = true. With spyk the real method runs by default, so you only override what you need. The pitfall with spyk is that real side effects still fire unless you stub them, which can cause unexpected I/O in a unit test.
- Senior
- spyk(realObject) creates a new spy that copies the real object's state, so it is not the same instance: code that still holds the original reference will not be recorded. Needing a spy often means the class does too much, so I prefer splitting it or using a fake. When I do use one, it is for a narrow case like checking that a real class calls a hook, and I avoid verifying call order, which is brittle.
How would you test a Hilt-injected use case that depends on a repository?
- Junior
- You can use @HiltAndroidTest with HiltAndroidRule, then replace the real binding with a fake using @TestInstallIn, @UninstallModules or @BindValue. The test runs with the Hilt graph and the fake is injected automatically.
- Mid
- For a fake used everywhere, a @TestInstallIn module in the test source set replaces the production module. For one class, @UninstallModules with a nested module or @BindValue on a field. Running it on the JVM needs Robolectric with @Config(application = HiltTestApplication::class). Hilt builds a new graph per test, so a @Singleton fake starts clean each time.
- Senior
- For pure use-case tests I skip Hilt entirely and pass a fake to the constructor, which is faster and has no Android dependency. Hilt testing is for integration tests where the wiring itself matters, such as a screen test that should use the real graph with only the data layer faked. I prefer @TestInstallIn over many @UninstallModules classes, because each @UninstallModules test class gets its own generated components and slows the build.
A test passes with a mock but fails in production. What went wrong?
- Junior
- The mock returned a canned value that the real implementation does not return, so the test did not exercise the real code path. The fix is to replace the mock with a fake that models the real behaviour.
- Mid
- The likely cause is that the mock bypassed real logic like null handling, error mapping, or async sequencing. The fix is to replace the mock with a fake that models the real behaviour, including edge cases like null, empty, and error responses. I also check whether the test verifies interactions instead of outcomes, which means it tests wiring not behaviour.
- Senior
- I audit the stubs for values the real contract never returns, or contract values (null, empty, errors) they never return, and check whether the test only verifies interactions. The lasting fix is shared fakes for our own data layer, plus tests that run the real repository against MockWebServer or an in-memory Room database, so the contract is checked against reality and not only against what the test author assumed.
What is screenshot testing in Android and when would you add it?
- Junior
- Screenshot testing renders a screen or component to an image and compares it to a stored reference image. I add it for screens where how things look matters, like a design system component or a checkout screen, so a theme or layout change that breaks them fails CI.
- Mid
- The tool renders the UI (with Roborazzi on Robolectric, or with layoutlib in Paparazzi or Compose Preview Screenshot Testing), saves reference images in record mode, and in verify mode renders again and fails if the difference is above a threshold. I start with shared design system components and a few key screens in their main states, plus dark mode and large font variants.
- Senior
- I treat screenshot tests as a review tool as much as a test: goldens live next to the code, so a pull request shows the visual change and a designer can approve it. To keep them reliable I render stateless composables with fixed state, record and verify in the same CI environment, and keep the threshold small. I also keep them focused, because a test that captures a whole app flow fails for many unrelated reasons and people stop reading the diffs.
How do you handle font and rendering differences between local machines and CI?
- Junior
- Use the same tool and the same machine type for recording and verifying. Do not record goldens on a Mac and verify them on Linux.
- Mid
- Text anti-aliasing and font metrics differ between operating systems and between JVM rendering and devices. I record goldens in CI, or in a pinned Docker image that matches CI, and verify in the same environment. I bundle the app's fonts and set a small difference threshold for leftover noise.
- Senior
- I make recording part of the pipeline: a job that re-records on the CI image and opens a commit or pull request with the new goldens, so nobody records locally. Tool and library upgrades (Robolectric, layoutlib, Compose) can change rendering, so I upgrade them in a separate pull request that re-records all goldens and gets a visual review. I avoid raising the threshold to hide environment problems, because that also hides real regressions.
Roborazzi versus Paparazzi versus Compose Preview Screenshot Testing: how do you choose?
- Junior
- All three render on the host without an emulator. Roborazzi uses Robolectric, Paparazzi uses layoutlib, and Compose Preview Screenshot Testing turns @Preview functions into tests.
- Mid
- Roborazzi runs inside normal Robolectric tests, so it can capture whole Activities, Views or Compose nodes, and works with tests that already use Robolectric or Hilt. Paparazzi uses layoutlib, does not need Robolectric, and gives a simple rule with snapshot calls for composables and Views. Compose Preview Screenshot Testing reuses @Preview functions with @PreviewTest in a screenshotTest source set, which is very little extra code if the team already writes previews.
- Senior
- I look at what the team already has and at maturity. If the screen tests already run on Robolectric, Roborazzi lets me add screenshots to them and capture after interactions. Paparazzi is a good fit for component libraries rendered in isolation, without Robolectric. Compose Preview Screenshot Testing is attractive for preview-heavy Compose code, but it is still experimental and its setup is moving from a standalone plugin to AGP test suites, so I would check the current docs and accept some churn. Whatever I pick, I standardise on one tool per module so goldens stay consistent.
A screenshot test is flaky in CI but passes locally. How do you debug it?
- Junior
- I look at the diff image from CI to see what changed. Then I check for things that change between runs, like the current time, network images or animations, and replace them with fixed values.
- Mid
- If the diff is only text edges, it is a rendering environment difference, so I make sure goldens are recorded in the same environment as CI. If content changes, I look for live data: the current time, a real image load, or a ViewModel starting work. I render the stateless composable with fixed state instead, and pause mainClock for animated UI.
- Senior
- I download the actual, expected and diff images from the CI artifacts and classify the change: environment (anti-aliasing, fonts), content (data, time, random values), or timing (animation frame, async load). Environment issues are fixed in the pipeline, not with a higher threshold. Content issues mean the test is not hermetic, so I pass fixed state. Timing issues mean the test captured while UI was still settling, so I control the clock with autoAdvance = false and advanceTimeBy, or wait for the condition with waitUntil before capturing.
A Compose end-to-end test fails sometimes because a node is not found, though it does appear on screen. What do you check first?
- Junior
- I check whether the data for that node comes from background work, like a network call. If the test checks before the data arrives, it fails. I would use composeRule.waitUntil with a condition instead of a sleep.
- Mid
- The Compose rule waits for recomposition and animations, so the usual cause is work it cannot see, such as a coroutine on Dispatchers.IO or a real network call. I replace the real backend with a fake through a Hilt test module, and if some async work must stay, I register an IdlingResource or use waitUntil. I also check for state left by earlier tests.
- Senior
- I look at the failure across runs: always at the same step points to timing, random steps point to shared state or environment. For timing I make the work visible to the framework (CountingIdlingResource or waitUntil) or remove it with fakes. For state I enable Test Orchestrator with clearPackageData. For environment I run on a Gradle Managed Device so CI matches local. Then I run the test many times on that device before calling it fixed, and I ask whether part of the test belongs in a faster local test.
What is the difference between Espresso and UI Automator, and when would you use each?
- Junior
- Espresso tests the UI of my own app. UI Automator can interact with other apps and system UI, like a permission dialog. I use Espresso in-app and UI Automator when I need to tap system UI.
- Mid
- Espresso runs in my app's process and works with the View hierarchy; it waits for the main thread and registered idling resources. UI Automator works at the device level through accessibility information, so it can reach any app or system UI. For Compose screens I use the Compose test APIs, which work alongside Espresso.
- Senior
- The key difference is synchronisation. Espresso and the Compose rule know when the app is idle, so in-app tests need few explicit waits. UI Automator does not, so it uses wait with Until conditions and timeouts, which makes it slower and easier to make flaky. I keep UI Automator to short steps, such as granting a permission, inside an otherwise Espresso or Compose test, and I avoid system UI entirely where I can, for example by granting permissions with GrantPermissionRule.
How does Android Test Orchestrator reduce flakiness?
- Junior
- It runs each test separately, so a crash or a static variable in one test does not affect the next.
- Mid
- It runs each test in its own instrumentation invocation. With the clearPackageData runner argument set to true, it also clears the app's data after each test, so databases, preferences and files do not leak between tests. You enable it with execution = ANDROIDX_TEST_ORCHESTRATOR and an androidTestUtil dependency on the orchestrator.
- Senior
- Isolation is the benefit and time is the cost: starting a fresh instrumentation per test adds overhead, so a big suite gets slower. I accept that for end-to-end tests because order-dependent failures are expensive to debug, and I keep the suite small. For a crash in one test, the orchestrator still reports the other tests instead of losing the whole run. For parallelism I use Gradle Managed Device sharding, which splits the suite across identical emulators.
A team has 200 end-to-end tests and 15 of them are flaky. What is your plan?
- Junior
- I would fix the flaky tests one by one, checking each for Thread.sleep, real network calls and animations, and replacing those with idling resources, fakes and disabled animations.
- Mid
- I would group the 15 by cause: async timing, shared state, animations or real I/O. Enabling the orchestrator with clearPackageData and animationsDisabled fixes whole groups at once. Then I add fakes or idling resources for the async ones. I would also question the 200: many probably check logic that belongs in local tests.
- Senior
- First I protect the pipeline: quarantine the known flaky tests into a non-blocking job, with an owner and a deadline, so the main suite is trusted again. Then I fix the shared causes in the setup (hermetic fakes through Hilt, orchestrator, disabled animations, managed devices) before touching individual tests. I track pass rate per test from CI history so we can see whether flakiness is going down, and I move tests that do not need a device into Robolectric or plain JVM tests so the end-to-end layer is small and covers only key journeys.