Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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.

CallbackStateWhat to Do
onCreate()CreatedInitialize UI (setContentView), restore saved state, setup ViewModel
onStart()VisibleStart animations, refresh data that may have changed
onResume()ForegroundRegister sensors/camera, resume video playback
onPause()Partially visiblePause video, save critical data quickly (keep this fast)
onStop()Not visibleRelease heavy resources, unregister receivers, save to database
onDestroy()DestroyedFinal 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:

CallbackPurpose
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:

StrategyUse CaseSurvives Process Death?
ViewModelBusiness data, network resultsNo (use SavedStateHandle)
onSaveInstanceStateUI state (scroll position, text input)Yes
configChanges in manifestVideo players, games, camera appsN/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?

ComponentPurposeHas UIEntry Point
ActivitySingle screen with UIYesIntent
ServiceBackground operationsNoIntent/Binding
BroadcastReceiverRespond to system/app eventsNoIntent broadcast
ContentProviderShare data between appsNoContent 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?

AspectApplication ContextActivity Context
LifecycleLives with appDies with Activity
UI OperationsCannot show dialogs, inflate themed viewsFull UI support
Memory SafetySafe in singletonsCan 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?

FlagEffect
FLAG_ACTIVITY_NEW_TASKStart in new task (required from non-Activity context)
FLAG_ACTIVITY_CLEAR_TOPPop activities above target, bring target to front
FLAG_ACTIVITY_SINGLE_TOPDon’t create new instance if already at top
FLAG_ACTIVITY_CLEAR_TASKClear 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.

ModeBehaviorUse Case
standardNew instance every timeMost activities
singleTopReuse if already at top (onNewIntent)Search results, notifications
singleTaskOne instance per task, clears aboveMain/Home screen
singleInstanceAlone in its own taskLauncher, 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

TopicKey Points
Activity LifecycleonCreate (init) → onStart (visible) → onResume (interactive) → reverse for shutdown
Fragment LifecycleAdditional onCreateView/onDestroyView; null binding in onDestroyView
Config ChangesViewModel survives; onSaveInstanceState for UI state; avoid configChanges
ComponentsActivity (UI), Service (background), BroadcastReceiver (events), ContentProvider (data sharing)
ContextApplication for singletons; Activity for UI; never store Activity in long-lived objects
Launch Modesstandard (new), singleTop (reuse at top), singleTask (one per task), singleInstance (own task)