Tasks and the Back Stack
In Sprout, the user opens the plant list, taps a Monstera, then taps Edit. Now they press Back twice. Where do they land each time? Android answers this with one simple data structure: a stack.
The rule
Start pushes, Back pops; a task is the stack.
A task is the collection of activities a user works with to do one job, kept as a back stack:
- Starting an activity pushes it on top. It becomes the one the user sees.
- Pressing Back pops the top activity. It is finished and destroyed, and the one underneath resumes.
- Calling
finish()in code pops the current activity, just like Back.
Each app launched from the home screen usually gets its own task, which is what you see as a card in the recents screen.
You can change the default "always push a new copy" behaviour when needed:
<activity android:name=".PlantListActivity"
android:launchMode="singleTop" />standard(default) — every start creates a new instance, even if one is already on the stack.singleTop— if the activity is already on top, reuse it (it receivesonNewIntent) instead of stacking a copy.singleTask— keep at most one instance in its task; starting it again clears the activities above it.
The intent flag FLAG_ACTIVITY_CLEAR_TOP does a similar clearing for one particular start.
The shortcut
Draw the stack as a column of names, newest on top. Every action is a push or a pop.
Open Sprout
Stack:
List.
The trap: after a form saves, forgetting to call finish(). The user presses Back and the form reappears, looking unsaved.
Drills
Answer fast — trust the rule.
The stack is List, Detail. The user taps Edit. What is the stack now?
What happens to the top activity when the user presses Back?
With the default launch mode, Detail is on top and it starts Detail again. What is on the stack?
Which launch mode reuses the activity only when it is already at the top of the stack?
After saving, Sprout's edit screen should not come back on Back. What should it call?
Remember
- Start pushes, Back pops; a task is the stack.
- Draw the column of names and apply each push or pop.
- Call
finish()when a screen's job is done; use launch modes only when the default stacking is wrong.
