Sparround

Context, tasks, back stack & launch modes

Context is the gateway to the app environment: resources, system services, file system, launching components. Two main kinds:

  • Application context — lives as long as the app. Give it to singletons and long-lived objects.
  • Activity context — dies with the activity. Needed for UI work (dialogs, inflation, theming).

Golden rule: if an object outlives the context, never hand it an activity context — memory leak.

A task is the stack of activities for one user "flow" (the back stack). It is LIFO: new activities push on top, back pops the top.

Launch modes (via manifest or intent flags):

  • standard — a new instance every time.
  • singleTop — no new instance if already on top; onNewIntent fires (notification-opened screens).
  • singleTask — one instance per task; if present, everything above is cleared and onNewIntent fires (home screens).
  • singleInstance — alone in its own task (rare: an in-call screen).
SituationWhich Context?
Showing a dialog or inflating a layoutActivity context (theme required)
Creating a Room/Retrofit singletonApplication context
Toasts / reading resourcesEither works
Storing in a static fieldApplication only (an activity would leak)

Real banking scenario: opening a transaction detail from a push notification. Without singleTop + onNewIntent, every push stacks a new instance and back shows the same screen repeatedly. taskAffinity and FLAG_ACTIVITY_NEW_TASK combinations also come up in the context of task hijacking attacks — naming the StrandHogg vulnerability is a strong signal.

🛠 Practice task

Tasks and context drill:

  • Hand an activity context to a singleton, close the activity and read LeakCanary's trace; then switch to applicationContext.
  • Give an activity launchMode="singleTop" and open it from a notification (or a repeat intent) — log that onNewIntent fires.
  • Inspect the stack with adb shell dumpsys activity activities.

Done when: you can predict singleTask behaviour on a stack of A → B → C before running it.

📚 Sources and documentation