Core Android Fundamentals


1. Activity Lifecycle

Q: Explain the Activity lifecycle and its callback methods.

The Activity lifecycle represents the states an Activity transitions through from creation to destruction. Proper lifecycle management is essential for resource handling and user experience.

Callback State What to Do
onCreate() Created Initialize UI (setContentView), restore saved state, setup ViewModel
onStart() Visible Start animations, refresh data that may have changed
onResume() Foreground Register sensors/camera, resume video playback
onPause() Partially visible Pause video, save critical data quickly (keep this fast)
onStop() Not visible Release heavy resources, unregister receivers, save to database
onDestroy() Destroyed Final cleanup, cancel non-ViewModel coroutines

Q: What triggers each callback?

  • onStart/onStop: Visibility changes (another Activity covers or uncovers)
  • onResume/onPause: Focus changes (dialog appears, split-screen)
  • onDestroy: User presses back, calls finish(), or system kills for memory

Q: What happens during configuration changes (rotation)?

The Activity is destroyed and recreated: onPause() → onStop() → onDestroy() → onCreate() → onStart() → onResume(). ViewModel survives this process. Use onSaveInstanceState() to preserve UI state (scroll position, form input).


2. Fragment Lifecycle

Q: How does Fragment lifecycle differ from Activity lifecycle?

Fragments have additional callbacks because they're tied to a host Activity and have a separate view lifecycle:

Callback Purpose
onAttach() Fragment attached to Activity—get context reference
onCreate() Initialize non-UI components, parse arguments
onCreateView() Inflate and return the fragment's layout
onViewCreated() Best place to setup UI, observers, click listeners
onDestroyView() View destroyed—must null out binding to prevent leaks
onDetach() Fragment detached from Activity

Q: Why is viewLifecycleOwner important?

The Fragment instance can outlive its view (e.g., on back stack). Using viewLifecycleOwner for LiveData/Flow observation ensures observers are removed when the view is destroyed, preventing memory leaks and crashes from updating dead views.

Q: What's the critical cleanup in onDestroyView()?

Always set _binding = null. The Fragment survives on the back stack, but holding view references prevents garbage collection of the entire view hierarchy.


3. Configuration Changes

Q: How do you handle configuration changes properly?

Three strategies:

Strategy Use Case Survives Process Death?
ViewModel Business data, network results No (use SavedStateHandle)
onSaveInstanceState UI state (scroll position, text input) Yes
configChanges in manifest Video players, games, camera apps N/A

Q: Why is configChanges in manifest discouraged?

It requires manual handling of all layout adjustments, breaks automatic resource selection (different layouts for orientations), and makes code harder to maintain. Use only for special cases like video playback.

Q: What's the size limit for onSaveInstanceState?

About 500KB. Use it only for small, essential UI state. For large data, use ViewModel with SavedStateHandle.


4. Android Components

Q: What are the four main Android components?

Component Purpose Has UI Entry Point
Activity Single screen with UI Yes Intent
Service Background operations No Intent/Binding
BroadcastReceiver Respond to system/app events No Intent broadcast
ContentProvider Share data between apps No Content URI

Q: Explain the three types of Services.

  1. Foreground Service: Shows persistent notification, continues when app is backgrounded (music player, fitness tracking). Required for long-running user-visible tasks.

  2. Background Service: No notification, heavily restricted since Android 8.0. Use WorkManager instead for most background work.

  3. Bound Service: Provides client-server interface via onBind(). Lives only while clients are bound to it.

Q: What are Service return values?

  • START_STICKY: Restart with null intent if killed—for ongoing tasks
  • START_NOT_STICKY: Don't restart—for tasks that can wait
  • START_REDELIVER_INTENT: Restart with last intent—for tasks that must complete

Q: When would you use a ContentProvider?

When sharing structured data with other apps (like Contacts or Calendar). Also useful for accessing data via URIs with CursorLoaders or for integrating with system features like search suggestions.


5. Context

Q: What's the difference between Application Context and Activity Context?

Aspect Application Context Activity Context
Lifecycle Lives with app Dies with Activity
UI Operations Cannot show dialogs, inflate themed views Full UI support
Memory Safety Safe in singletons Can cause leaks if held long-term

Q: When to use each?

Application Context:

  • Singletons (database, analytics, image loader)
  • Starting services
  • Registering long-lived receivers
  • Anything that outlives an Activity

Activity Context:

  • Showing dialogs (requires Activity window)
  • Inflating views with correct theme
  • Starting Activities with proper task stack
  • Creating themed UI components

Q: How do memory leaks happen with Context?

Storing Activity Context in a static/singleton object prevents the Activity from being garbage collected. The entire Activity hierarchy stays in memory. Always convert to applicationContext when storing in long-lived objects.


6. Intents

Q: What's the difference between explicit and implicit Intents?

Explicit Intent: Specifies the exact component to start by class name. Used for internal app navigation.

Implicit Intent: Declares an action and lets the system find matching components. Used for cross-app functionality (share, view URL, send email).

Q: What are Intent flags and when do you use them?

Flag Effect
FLAG_ACTIVITY_NEW_TASK Start in new task (required from non-Activity context)
FLAG_ACTIVITY_CLEAR_TOP Pop activities above target, bring target to front
FLAG_ACTIVITY_SINGLE_TOP Don't create new instance if already at top
FLAG_ACTIVITY_CLEAR_TASK Clear entire task before starting

Q: What's a PendingIntent?

A token that grants another app permission to execute an Intent on your behalf—used for notifications, widgets, and alarms. Specify mutability (MUTABLE/IMMUTABLE) for security on Android 12+.


7. Launch Modes

Q: Explain Activity launch modes.

Mode Behavior Use Case
standard New instance every time Most activities
singleTop Reuse if already at top (onNewIntent) Search results, notifications
singleTask One instance per task, clears above Main/Home screen
singleInstance Alone in its own task Launcher, call screen

Q: What's onNewIntent() and when is it called?

Called instead of creating a new instance when using singleTop (and Activity is at top) or singleTask (and Activity exists in task). Extract new extras here instead of onCreate().


8. Process and App Lifecycle

Q: How does Android prioritize processes for killing?

From least to most likely to be killed:

  1. Foreground (visible Activity, foreground Service)
  2. Visible (partially obscured Activity)
  3. Service (background Service running)
  4. Cached (background Activities, stopped)
  5. Empty (no active components)

Q: How do you handle process death?

  • ViewModel data is lost—use SavedStateHandle for critical state
  • onSaveInstanceState() is called before process death
  • Test with "Don't keep activities" developer option
  • Activities are recreated with saved Bundle when user returns

Quick Reference

Topic Key Points
Activity Lifecycle onCreate (init) → onStart (visible) → onResume (interactive) → reverse for shutdown
Fragment Lifecycle Additional onCreateView/onDestroyView; null binding in onDestroyView
Config Changes ViewModel survives; onSaveInstanceState for UI state; avoid configChanges
Components Activity (UI), Service (background), BroadcastReceiver (events), ContentProvider (data sharing)
Context Application for singletons; Activity for UI; never store Activity in long-lived objects
Launch Modes standard (new), singleTop (reuse at top), singleTask (one per task), singleInstance (own task)

results matching ""

    No results matching ""