This guide covers six areas that senior Android interviews can probe. Each has a diagram, short explanations and questions with model answers.
To answer well, use four steps: state the mechanism, name how it fails, give your choice and its trade-off, then say how you would measure it. Code samples are short sketches, not production code.
Contents
- Android fundamentals
- Kotlin concurrency
- Architecture and data
- Performance
- Security
- Production engineering
1. Android fundamentals
Android can destroy your screens, or your whole process, at any time. Good apps treat memory as temporary and can rebuild the UI from saved state.
onCreate ---> onStart ---> onResume (interactive)
^ ^ | ^
| | v |
| onRestart onPause (focus lost)
| | |
| | v
| +---------- onStop (not visible)
| : \
| : +--> onDestroy
| v (finish or recreation)
| [process killed]
| | no further callbacks
| v
+------------ user returns: new process + saved Bundle
1.1 Activity lifecycle
| Callback | Meaning | Typical work |
|---|---|---|
onCreate |
Instance created | Set content, restore state |
onStart |
Visible | Start UI observation |
onResume |
Foreground and interactive | Resume interaction-only work |
onPause |
Losing focus, may still be visible | Keep it very short |
onStop |
No longer visible | Release UI resources, persist drafts |
onDestroy |
Instance going away | Clean up; not guaranteed to run |
- When A opens B:
A.onPause→B.onCreate→B.onStart→B.onResume→A.onStop. A translucent B leaves A withoutonStop. - A configuration change recreates the Activity by default. A
ViewModelsurvives it. - In multi-window, a paused Activity can still be visible. Tie UI collection to
STARTED, notRESUMED. UseonTopResumedActivityChangedfor exclusive resources. - On large screens, apps targeting Android 17 can no longer opt out of ignored orientation and resizability limits. Design for resizing.
1.2 Process death
The system can kill a background process to reclaim memory, without calling onDestroy. If the user returns to the task, Android creates a new process and restores the back stack.
| State holder | Rotation | System process death | Use for |
|---|---|---|---|
| Plain fields, singletons | Singletons only | Lost | Caches you can rebuild |
ViewModel |
Survives | Lost | Screen UI state |
SavedStateHandle, rememberSaveable
|
Survives | Survives | IDs, query text, small selections |
| Room, DataStore, files | Survives | Survives | Durable user data |
Saved state is not durable storage: it is discarded when the user dismisses the task. It travels through Binder, whose buffer of about 1 MB is shared by the process, so save IDs rather than lists. To test, background the app, run adb shell am kill <package>, then reopen it from Recents.
1.3 Services and background work
A service is a component, not a thread. Its callbacks run on the main thread.
| Need | Choose |
|---|---|
| Work only while the screen is relevant | Coroutine in viewModelScope
|
| Deferrable work that must survive restarts | WorkManager (periodic minimum is 15 minutes) |
| Ongoing work the user can perceive | Foreground service with a declared type and notification |
| Large transfer the user asked for | User-initiated data transfer job (Android 14+) |
| API offered to another component or app | Bound service |
| Alarm at an exact user-chosen time |
AlarmManager exact alarm, where permitted |
-
START_NOT_STICKYdoes not recreate the service.START_STICKYmay recreate it with a null intent.START_REDELIVER_INTENTredelivers the last intent. - Android 12+ restricts starting foreground services from the background. Android 14+ requires a service type.
- For apps targeting Android 15+,
dataSyncandmediaProcessingservices each get 6 hours in any 24; bringing the app to the foreground resets the timer. InonTimeout, callstopSelf()within seconds.
1.4 Threading
The main thread runs a Looper that takes messages from a MessageQueue one at a time. Input, lifecycle callbacks and frame work all share it. One slow task delays everything behind it.
- At 60 Hz a frame has about 16.7 ms; at 120 Hz about 8.3 ms.
- Incoming Binder calls run on a thread pool, so a
ContentProvideror AIDL service must be thread-safe. - Use
StrictModein debug builds to catch disk and network access on the main thread. - Apps targeting Android 17 get a lock-free MessageQueue. Check libraries that reflect on its private internals.
1.5 Memory management
ART garbage collection frees objects that are unreachable from GC roots. A leak is an object you no longer need that is still reachable.
- Common leaks: an Activity held by a singleton, unremoved listeners, delayed
Handlermessages, a Fragment keeping its view binding afteronDestroyView, aWebViewnot destroyed. - Churn (many short-lived allocations) causes GC pressure. Bitmaps are often the largest cost: decode at display size and use an image loader.
- Respond to
onTrimMemory. From Android 14, rely onTRIM_MEMORY_UI_HIDDENandTRIM_MEMORY_BACKGROUND. - The low-memory killer removes less important processes first: cached before service, visible and foreground.
- Android 17 adds RAM-based app memory limits. The release notes say such kills show
MemoryLimiterinApplicationExitInfo.getDescription. - Tools: LeakCanary, Memory Profiler, heap dumps and
ApplicationExitInfo(Android 11+).
Interview questions: fundamentals
Q1. A user fills a long form, takes a call, returns, and it is empty. Rotation works. Why?
The state lives only in a ViewModel, so it survives rotation but not process death. Put small keys in SavedStateHandle and autosave the draft to Room. Reproduce it with am kill.
Q2. Is onDestroy a safe place to save data?
No. A killed process gets no callback. Save as the user edits, or by onStop at the latest.
Q3. You must upload a 500 MB video that the user just selected. What do you use?
On Android 14+, a user-initiated data transfer job. On older versions, WorkManager with foreground execution. Make the upload chunked and resumable with a server upload ID, so a restart does not begin again.
Q4. Heap grows after each visit to one screen. How do you debug it?
Open and close it several times, force GC and take a heap dump. Find destroyed instances still retained, then follow the shortest path to a GC root. Fix ownership; a WeakReference often only hides the bug.
Q5. What is the difference between a leak, churn and an OOM?
A leak retains unneeded objects. Churn allocates and frees too fast, causing GC work. An OOM is an allocation that cannot be satisfied; a leak is one cause, a single huge bitmap is another.
Q6. Why can a BroadcastReceiver lose work?
The process can lose importance once onReceive returns. goAsync buys a little time but stays within the broadcast timeout. Enqueue WorkManager for anything longer.
2. Kotlin concurrency
Every coroutine should have an owner that can cancel it, wait for it and see its failure.
viewModelScope (SupervisorJob)
| |
launch: load screen launch: refresh badge
(coroutineScope) (unaffected if load fails)
| |
async: profile async: feed
(throws) (gets cancelled)
Clearing the ViewModel cancels everything.
Handle the error in load: an uncaught one can still crash the app.
2.1 Coroutines and dispatchers
A coroutine is a computation that can suspend without blocking its thread. suspend does not move work to another thread. A suspend function should be main-safe: the function that does blocking work switches dispatcher itself.
| Dispatcher | Use | Note |
|---|---|---|
Main / Main.immediate
|
UI work |
immediate skips a re-dispatch if already on main |
Default |
CPU work | Sized around CPU cores |
IO |
Blocking I/O | Larger elastic pool; limit with limitedParallelism
|
2.2 Structured concurrency
A child inherits its parent's context. The parent completes only after its children. Cancelling a parent cancels them all.
| Scope | Failure of one child | Use |
|---|---|---|
coroutineScope |
Cancels siblings and fails the scope | All results are required |
supervisorScope |
Siblings continue | Independent results |
-
launchpropagates an uncaught exception at once.asyncexposes it atawait, but a failing childasyncstill cancels a regular parent. -
CoroutineExceptionHandlerworks for uncaught exceptions in rootlaunchcoroutines, including direct children of a supervisor scope. It is not a recovery tool. - Avoid
GlobalScope. Inject an application scope for work that must outlive a screen. It still dies with the process.
suspend fun loadHome(): Home = supervisorScope {
val profile = async { api.profile() } // required
val ads = async { // optional
try { api.ads() } catch (e: IOException) { emptyList() }
}
Home(profile.await(), ads.await())
}
2.3 Cancellation
Cancellation is cooperative. Library suspend functions such as delay check for it. CPU loops must call ensureActive() or yield(). Blocking calls need runInterruptible or an API with its own cancel hook.
- Rethrow
CancellationException. Bothcatch (e: Exception)andrunCatchingcan swallow it. - Use
withContext(NonCancellable)only for short suspending cleanup infinally. -
withTimeoutcancels cooperatively. It cannot undo a server request that already succeeded.
2.4 Flow
| Type | Behaviour | Use |
|---|---|---|
Flow (cold) |
Producer runs for each collector | Queries, request pipelines |
StateFlow |
Hot, has a current value, drops equal values, conflates | UI state |
SharedFlow |
Hot, configurable replay and buffer | Broadcasts to several collectors |
Channel |
Each element goes to one receiver | Work queues |
-
flowOnchanges the upstream context only.catchhandles upstream errors only. -
bufferdecouples producer and consumer.conflateskips intermediate values.collectLatestcancels the old block. -
flatMapLatestsuits search.flatMapConcatkeeps order.flatMapMergeruns concurrently. - Wrap callback APIs with
callbackFlowand unregister inawaitClose. - Collect with
collectAsStateWithLifecyclein Compose, orrepeatOnLifecyclein Views. - A
SharedFloworChanneldoes not guarantee that a one-off UI event is handled. Model important outcomes as state that the UI acknowledges.
val results: StateFlow<List<Item>> = query
.debounce(300)
.distinctUntilChanged() // unnecessary if query is already a StateFlow
.flatMapLatest { q -> repo.search(q).catch { emit(emptyList()) } }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
In production, return an error state instead of an empty list. If query is a StateFlow, remove the distinctUntilChanged line.
2.5 Race conditions
Races happen even on one thread, because other coroutines run while one is suspended. Typical cases are check-then-act, stale responses overwriting new ones, and two token refreshes.
| Tool | Fits |
|---|---|
MutableStateFlow.update |
Atomic state change; the lambda may rerun, so no side effects |
Mutex.withLock |
A critical section that suspends; not reentrant |
limitedParallelism(1) |
Confines non-suspending sections; others interleave at suspension points |
Single consumer of a Channel
|
Strict serial processing |
| Database transaction or unique constraint | Invariants on persisted data |
private val lock = Mutex()
private var cached: Config? = null
suspend fun config(): Config = lock.withLock {
cached ?: api.fetchConfig().also { cached = it }
}
Interview questions: concurrency
Q1. Does viewModelScope.launch { api.pay() } guarantee payment completes?
No. Clearing the ViewModel cancels it, and the process can die. Cancellation also does not prove the server did nothing. Persist the intent, send an idempotency key and reconcile with the server.
Q2. What is wrong with runCatching around a suspend call?
It catches CancellationException, so cancelled work may continue and look like an error. Catch expected exception types, or rethrow cancellation first.
Q3. StateFlow or SharedFlow for navigation after login?
Prefer state such as loggedIn, which the UI reads and acts on. It survives collector restarts. A replay-0 SharedFlow drops the event with no subscriber.
Q4. How do you run 1,000 uploads with at most 4 in flight?
Use 4 workers reading a channel, or flatMapMerge(concurrency = 4). A Semaphore(4) also limits calls, but still creates 1,000 coroutines. Persist the queue if it must survive process death.
Q5. How do you test time-based Flow logic?
Use runTest, inject dispatchers and advance virtual time. Collect hot flows in backgroundScope. Avoid real sleeps.
Q6. Does Dispatchers.Main make code race-free?
It removes parallel access between main-thread blocks. It does not make a multi-step suspend operation atomic.
3. Architecture and data
Give each piece of data one source of truth. State flows down to the UI and events flow back up.
UI (Compose) <--> ViewModel <--> Repository
^
|
v
Room: SOURCE OF TRUTH
(entities, outbox, cursor)
^
|
v
Sync worker (WorkManager)
^
push: ops + opId | pull: changes after cursor
v
Server API (versions, deduplication)
3.1 MVVM
The View renders state and sends events. The ViewModel turns data into an immutable UI state and handles those events. The Model is the data and business logic. A ViewModel must not hold an Activity, a View or a UI Context.
Model loading, content and errors so that impossible combinations cannot occur. A sealed type suits exclusive states. A data class suits screens that show cached content while refreshing. When strict event ordering matters, MVI adds a single reducer.
3.2 Clean Architecture
Source-code dependencies point toward business rules. The domain defines repository interfaces, and the data layer implements them.
| Layer | Contains | Depends on |
|---|---|---|
| Presentation | Composables, ViewModels, UI state | Domain |
| Domain | Entities, use cases, repository interfaces | Pure Kotlin only |
| Data | Repository implementations, Room, network, mappers | Domain |
This differs from Google's recommended layering, where the domain layer is optional and sits above the data layer. Add use cases when they hold real rules or are reused. One-line pass-through classes only add cost. In large apps, split by feature module and keep each public API small.
3.3 Room
- DAOs that return
Flowemit again when observed tables change. Unrelated row changes can trigger this, so usedistinctUntilChangedwhere useful. - Use
@TransactionorwithTransactionfor writes that must succeed together. Keep network calls outside transactions. - Add indexes for real filters and joins, then check with
EXPLAIN QUERY PLAN. Page large lists. - Export schemas and test every supported upgrade path with
MigrationTestHelper. - Destructive migration deletes user data, including unsynced edits.
3.4 Offline-first design
The UI reads only from the local database. The network updates the database. A user edit is saved locally first and shown with a pending status.
Use the outbox pattern: in one transaction, update the entity and insert an operation row. A worker sends the rows later.
suspend fun rename(id: String, title: String) = db.withTransaction {
notes.updateTitle(id, title, SyncState.PENDING)
outbox.insert(Op(opId = uuid(), noteId = id, type = RENAME, payload = title))
}
// Then enqueue unique sync work. Also reconcile on app start,
// in case the process died between the commit and the enqueue.
3.5 Synchronization
-
Push: send operations in order for each entity. Use the same
opIdon every retry, and have the server deduplicate it (idempotency). - Pull: request changes after a server-issued cursor. Apply the changes and the new cursor in one transaction.
- Deletes: send tombstones, or other devices cannot learn that a row was removed. Define a full resync for expired cursors.
- Retries: use exponential backoff with jitter for temporary errors. Do not retry permanent errors forever; surface them.
- Triggers: WorkManager unique work with a network constraint, app foreground, and push messages as hints. Push delivery is not guaranteed.
-
Race: if new rows arrive while a worker is finishing,
KEEPcan miss them.APPEND_OR_REPLACEor a re-check closes the gap.
3.6 Conflict resolution
A conflict occurs when two writers change the same base version. Detect it with a server version or ETag: the server rejects a stale write, for example with HTTP 409 or 412.
| Strategy | Good for | Cost |
|---|---|---|
| Last write wins | Low-value settings | Silently loses data; device clocks are unreliable |
| Server wins | Prices, stock, permissions | Discards local intent unless you tell the user |
| Field-level three-way merge | Forms with separate fields | Needs the base version; same-field clashes remain |
| Ask the user | Valuable documents | More UI and delay |
| Domain operations | Counters: send +1, not the total | Server must apply and deduplicate operations |
| CRDT | Collaborative editing | Complex, with metadata overhead |
Do not overwrite a row that has pending local edits with a pulled copy. Rebase the pending operations on the new server version.
Interview questions: architecture and data
Q1. Design an offline notes app.
Cover client-generated IDs, Room as source of truth, an outbox, cursor-based pull, tombstones and versions. Then state the conflict rule per field, the sync status the user sees, and what happens on logout with unsent edits.
Q2. The request succeeded but the response was lost. What happens?
The client retries with the same operation ID. The server returns the stored result instead of applying it again. WorkManager alone cannot give exactly-once effects.
Q3. When is Clean Architecture too much?
For a small app with simple CRUD and one team. Keep UI and data separation, and add a domain layer when rules grow or are shared.
Q4. Where do you map DTOs?
At the data boundary. Separate DTO, entity and domain models stop API or schema changes leaking into UI. Merge them only when the cost clearly outweighs the isolation.
Q5. How do you ship a risky schema migration?
Test from every old version with realistic data. Prefer additive changes. Roll out in stages and watch crashes. Plan to fix forward, because an installed schema cannot simply be rolled back.
4. Performance
Measure on a real, lower-end device with a release-like build, change one thing, then measure again. Debug builds give misleading timings.
MAIN THREAD (a Compose frame)
input/animation -> composition -> layout -> drawing
(what) (where) (record commands)
|
v
SurfaceFlinger + display <------------ RenderThread + GPU
Frame interval: ~16.7 ms at 60 Hz, ~8.3 ms at 120 Hz
4.1 Profilers and tools
| Question | Tool |
|---|---|
| Where is CPU time going? | Android Studio CPU profiler |
| What retains memory? | Memory Profiler, heap dump, LeakCanary |
| Why was this frame or startup slow? | Perfetto system trace |
| Did my change help, repeatably? | Macrobenchmark (user journeys), Microbenchmark (hot code) |
| Is it happening to real users? | Android vitals, JankStats, your own telemetry |
| Why does Compose recompose? | Layout Inspector recomposition counts, compiler reports |
4.2 Perfetto
Perfetto shows threads, CPU scheduling, frames, Binder calls and custom sections on one timeline. Add sections with androidx.tracing.
- Find the slow frame or startup window.
- Inspect the main thread and RenderThread.
- Check each thread state. Running means executing code. Runnable means waiting for a CPU. Sleeping often means waiting on a lock, Binder or another thread. Uninterruptible sleep often points to I/O.
- Follow the wake-up or Binder reply to the real blocker.
In PerfettoSQL, query the trace to compare many slices or runs.
4.3 ANRs
Default timeouts below are for AOSP and Pixel devices and can vary by manufacturer. Broadcast figures are for Android 14+; the longer end applies to CPU-starved processes.
| ANR type | Timeout |
|---|---|
| Input dispatch, including no focused window | 5 s |
| Broadcast, foreground priority | 10 to 20 s |
| Broadcast, background priority | 60 to 120 s |
| Executing service, foreground / background | 20 s / 200 s |
Common causes are main-thread I/O, lock contention, deadlock, slow synchronous Binder calls, heavy startup work and CPU starvation. Read all thread stacks. If the main thread waits on a lock, find its holder. An idle nativePollOnce stack may mean the dump missed the real problem.
4.4 Startup
| Type | Starting point |
|---|---|
| Cold | No process: create process, Application, Activity, first frame |
| Warm | Part of the work is reused, for example the process lives but the Activity is recreated |
| Hot | Existing Activity is brought to the foreground |
-
TTID is time to the first frame. TTFD is time until content is usable; report it with
reportFullyDrawn. - Check
ContentProviderinitializers from libraries,Application.onCreate, dependency graph creation and disk reads. - Defer or lazy-load work. Moving it to a background thread does not help if the first frame waits for it.
- Baseline Profiles compile important paths ahead of time. Startup Profiles improve DEX layout. Use R8 and verify with Macrobenchmark.
4.5 Rendering
A frame goes through input, animation, measure, layout and draw on the main thread. RenderThread then issues GPU work and SurfaceFlinger composes the screen. Jank is a frame that misses its deadline. Android vitals also treats frames over 700 ms as frozen. Look for deep or repeated layout, large bitmaps, overdraw and allocations during drawing.
4.6 Compose performance
Compose works in three phases: composition (what to show), layout (where) and drawing (how). A state read invalidates from the phase where it happens, so read fast-changing state as late as possible.
// Reads in composition: recomposes on every scroll change
Modifier.offset(y = scroll.value.dp)
// Reads in layout (placement): skips recomposition
Modifier.offset { IntOffset(0, scroll.value) }
The snippet shows read timing only; the two use different units.
- Give lazy list items stable, unique
keys, and acontentTypefor mixed lists. - Use
rememberfor expensive calculations. UsederivedStateOfwhen inputs change more often than the result. - Strong skipping is on by default since Kotlin 2.0.20. Unstable parameters are compared by instance, stable ones by
equals. - Do not mutate a list in place. Use immutable data and produce a new value.
- Avoid backwards writes: changing state after it was read in the same composition.
- Profile before adding
@Stableor@Immutable. They are promises the compiler trusts.
Interview questions: performance
Q1. Cold start regressed after a release. How do you investigate?
Confirm it in field data by version and device. Reproduce with Macrobenchmark, compare Perfetto traces and diff startup work, including new SDK initializers. Fix the largest blocker and add a regression check.
Q2. ANRs occur only on low-end devices, with no clear app frame.
Group by ANR type, device and OS. Look for CPU starvation, memory pressure, I/O and Binder waits. Add trace sections and breadcrumbs, then reproduce under load.
Q3. A list stutters while scrolling.
Measure a release build. Separate composition, image decoding and main-thread work in a trace. Check keys, unstable data, sorting inside composables and oversized images.
Q4. Why can an average hide a problem?
A few slow devices or sessions disappear in it. Track P50, P90 and P99, split by device class and app version.
5. Security
Treat the app and device as an environment an attacker may control. The server must enforce authorization, and no secret shipped in the app stays secret.
Authorization code flow with PKCE:
App Browser tab Auth server Resource API
|--1. login + challenge-->| | |
| |--2. authorize---------->| |
| |<-3. sign-in, code-------| |
|<-4. redirect---| | |
|--5. code + code_verifier---------------->| |
|<-6. verifier matches: tokens-------------| |
|--7. API call with access token--------------------------->|
5.1 Android Keystore
Keystore performs operations with keys while keeping key material out of your app process. Keys can be backed by a TEE or, on some devices, StrongBox. Check the actual security level instead of assuming it.
- Keystore protects keys, not data. Encrypt data with AES-GCM and store the ciphertext and IV. Never reuse an IV with the same key; let the cipher generate it.
- A compromised app process may be unable to extract a key but can still use it.
- For sensitive actions, require user authentication and bind
BiometricPromptto aCryptoObject. - Handle lost or invalidated keys. A new biometric enrollment can invalidate some keys. Keystore keys do not move with backups, so restored ciphertext may be unreadable. Re-authenticate.
- All APIs in Jetpack
security-crypto, includingEncryptedSharedPreferences, are deprecated. For new code, one option is Keystore directly, or a maintained library such as Tink, with DataStore.
5.2 OAuth 2.0 and OpenID Connect
OAuth 2.0 grants access to APIs. OIDC adds authentication through an ID token. A mobile app is a public client.
- Use the authorization code flow with PKCE in the system browser or a Custom Tab, not an embedded WebView. Do not rely on a client secret.
-
RFC 9700 requires PKCE for public clients.
S256is the method to use. The password grant must not be used, and the implicit grant should not be. - Prefer verified App Links for the redirect. Validate
state, and for OIDC thenonce. - Validate the ID token's signature, issuer, audience and expiry. A backend that creates a session must validate it itself.
- For native sign-in with passkeys, passwords or federated identity, look at Credential Manager.
| Token | Audience | Rule |
|---|---|---|
| Access token | Resource API | Short-lived; the client should not depend on its contents |
| Refresh token | Authorization server | Protect strongly; never send to resource APIs |
| ID token | Client app | Proof of sign-in; do not use it to call APIs |
5.3 Token lifecycle
The lifecycle is issue, store, use, refresh, revoke and delete. For public clients, RFC 9700 requires refresh tokens to be sender-constrained or rotated.
- Allow one refresh at a time. Parallel refreshes with rotation can look like token theft and end the session.
- Inside the lock, check whether another caller already refreshed.
- Persist the new refresh token before using the new access token.
- Retry a failed request once. Log out on
invalid_grant, not on a network timeout or a server 5xx. - On logout, cancel work, revoke tokens if supported, and clear local user data. Decide first what happens to unsent edits.
suspend fun refreshIfStale(used: String): String = mutex.withLock {
val current = store.read()
if (current.access != used) return@withLock current.access
val fresh = authApi.refresh(current.refresh)
store.write(fresh)
fresh.access
}
With OkHttp, an Authenticator handles 401 responses. It is a blocking API, so bridge to this function with care, use a separate client for refresh calls and cap retries.
5.4 Secure networking
- Use TLS everywhere. Cleartext is disabled by default for apps targeting API 28+. Control exceptions in Network Security Config.
- Never install a trust-all
TrustManageror an allow-all hostname verifier. - Pinning limits which keys are trusted, but a bad rotation can cut off installed apps. If your threat model needs it, add backup pins, an expiry and a rotation runbook.
- Keep tokens and personal data out of logs, URLs and crash reports.
5.5 Threat modeling
Ask four questions: What are we building? What can go wrong? What will we do? Did it work? STRIDE helps with the second.
| Threat | Android example | Mitigation |
|---|---|---|
| Spoofing | Another app claims the redirect scheme | PKCE, verified App Links |
| Tampering | Modified client sends a lower price | Server calculates and validates |
| Repudiation | User disputes a payment | Server audit trail |
| Information disclosure | Token written to logs | Redaction, safe storage |
| Denial of service | Malformed deep link crashes the app | Validate all input |
| Elevation of privilege | Exported component runs an internal action |
exported=false, permissions, caller checks |
Also review PendingIntent mutability (immutable unless mutation is required), WebView JavaScript bridges, FileProvider paths and third-party SDKs. Play Integrity gives a risk signal that your server verifies; it does not replace authorization.
Interview questions: security
Q1. How do you hide an API secret in an APK?
You cannot. Obfuscation and NDK code only slow extraction. Keep privileged secrets on a backend that authenticates, authorizes and rate-limits.
Q2. What attack does PKCE stop?
Someone who intercepts the authorization code cannot exchange it without the code_verifier. It does not protect tokens already stolen from a compromised device.
Q3. Ten requests get 401 together. What happens?
One refreshes under a lock; the others see the new token and reuse it. Each retries once. Only a confirmed invalid refresh token ends the session. Account for a lost rotation response, which depends on server policy.
Q4. Does root detection solve security?
No. It is a bypassable signal that can block legitimate users. Combine risk signals with server-side checks.
6. Production engineering
Assume every release can fail. Limit how many users it reaches, detect problems quickly and keep a way to stop the damage.
CI checks -> signed App Bundle -> testing tracks -> small rollout
^ (+ mapping file) |
| v
| expand in steps <--yes-- healthy?
| (re-check each) | no
| v
+---- fix forward (higher version code) <---- halt + mitigate
6.1 Crash reporting
- Use a tool such as Firebase Crashlytics or Sentry next to Android vitals.
- Upload the R8 mapping file and native symbols for every build.
- Record app version, device, OS, flag states and breadcrumbs. Never record tokens or unnecessary personal data.
- Report meaningful non-fatal errors. A custom uncaught-exception handler must delegate to the previous one.
- Use
ApplicationExitInfoto learn why earlier processes ended. - Rank issues by affected users and journeys, not only event counts.
6.2 Android vitals
Exceeding a bad behavior threshold can reduce your visibility on Google Play. These are the published thresholds for stability and wake locks, checked 1 December 2026.
| Core vital | Overall | Per phone model |
|---|---|---|
| User-perceived crash rate | 1.09% | 8% |
| User-perceived ANR rate | 0.47% | 8% |
| Excessive partial wake locks | 5% | No threshold listed |
The same page lists memory usage (anonymous RSS + swap) and bitmap memory as core vitals for mobile apps. Memory limits depend on device RAM and app state. For apps, foreground memory on a 4 GB device is limited to 2.00 GB. Bitmap limits are 200 MB for background and user-perceived services, and 400 MB for cached. Store visibility effects for memory may start in February 2027. The page also sets watch-specific thresholds and a code optimization check. Treat all thresholds as limits, not targets.
6.3 Staged rollouts
- Go from internal and closed testing to a small percentage, then increase in steps.
- Before starting, define the metrics, the halt limits, the observation time and the owner.
- Halting stops further distribution. It does not downgrade users who already updated. Ship a fix with a higher version code.
- Percentage rollout applies to updates, not an app's first release.
- Compare the new version with the old one. A small sample may not show rare crashes.
6.4 Feature flags
Flags separate deploying code from releasing a feature.
- Ship safe defaults that work offline, and cache the last good values.
- Keep values stable during a user journey. Log which variant ran.
- A kill switch only works if the app fetches it and the flag is checked before the failing code.
- Flags are not authorization. Every flag needs an owner and a removal date.
- Keep database and API changes backward compatible while old versions remain installed.
6.5 CI/CD
Each pull request should compile, run lint and static analysis, and run unit tests. Add instrumented, screenshot, migration and performance tests where risk justifies the time.
- Build one signed App Bundle and promote that same artifact through tracks.
- Keep signing credentials in a secret manager, never in the repository or in jobs for untrusted pull requests. Use Play App Signing.
- Pin dependencies and scan them. Generate unique version codes.
- Test the R8 release build, because shrinking can break reflection or serialization.
6.6 Incident response
- Detect through an alert, vitals or support.
- Triage impact and severity. Name an incident lead.
- Mitigate first: kill switch, server change or halted rollout.
- Communicate at agreed intervals.
- Fix and verify with a staged release.
- Learn through a blameless review with owners and due dates.
Interview questions: production
Q1. Crashes double at a 5% rollout. What do you do?
Halt the rollout and confirm the signal by version and device. Disable the suspect feature if a flag covers it. Ship a higher-version hotfix, stage it and add the missing test or alert.
Q2. The app crashes on launch before flags load. What now?
The remote switch may be unreachable. Halt the rollout, apply any compatible server-side mitigation and ship a fix. To prevent repeats, use safe cached defaults, delay risky initialization and consider crash-loop detection.
Q3. A backend change breaks old app versions.
Restore compatibility on the server first. Then use contract tests, API versioning and tolerant parsing. A forced update is a last resort.
Q4. How do you decide to ship?
Use agreed gates: stability, ANRs, startup, key journey success and business guardrails. Name who can override a gate and how that risk is recorded.
Q5. Behavioural: describe an incident you handled.
Use your own example: impact, your decisions, mitigation, root cause and what changed afterwards. Do not invent one.
Final thought
The same habits run through all six topics: assume the process can die, give every task an owner, keep one source of truth, measure before optimizing, trust the server for security decisions, and keep a way to stop a bad release.
Android platform rules and Google Play thresholds change. Check the linked official pages before relying on a specific number.
Author: Padmakar Garg
Android Developer with 8+ years of experience in Kotlin, Java, Jetpack Compose, Kotlin Multiplatform, scalable architecture, mobile security, and high-performance app development.
Top comments (0)