


AAMobile apps can be interrupted at any time by incoming calls, OS memory pressure, or user actions. A strong engineer should know how to preserve a good user experience when the app is paused, backgrounded, or killed.
Explain how you would handle the lifecycle of a mobile application and save state when it is abruptly sent to the background.
Your answer should cover:
The interviewer expects a practical systems explanation rather than platform-specific trivia. Discuss lifecycle callbacks/events, in-memory vs persistent state, trade-offs around performance and consistency, and common mistakes such as saving too much or relying on background execution guarantees.
Mobile operating systems move apps through states such as active, inactive, background, suspended, and terminated. Engineers must attach state-saving logic to the last reliable lifecycle events before the app may be killed.
def on_background(state):
persist_state(state)
Not all state should be saved. Small UI state, navigation position, draft text, and unsynced user actions are usually persisted, while large caches or easily recomputed data should be rebuilt later.
state = {
'screen': current_screen,
'draft': draft_text,
'scroll': scroll_offset
}
To restore state after process death, in-memory objects must be serialized into a durable format such as JSON, key-value storage, or a local file. The saved representation should be compact, versioned, and resilient to partial writes.
import json
payload = json.dumps(state)
Restoration logic should be safe to run multiple times and should tolerate missing or stale data. A good design validates saved state before applying it and falls back to defaults when needed.
saved = load_state() or {}
screen = saved.get('screen', 'home')
Apps should not assume they will get long background execution time. Critical user data should be flushed quickly and locally first, then synced remotely when the app is active again.
queue.append(user_action)
persist_queue(queue)