The Activity Lifecycle
Sprout's detail screen shows a live countdown to the next watering. If the user switches to another app, that countdown should stop wasting battery, and when they return it should pick up again. To do that you need to know exactly when the system tells your activity it is visible, in front, or gone.
The rule
Up: create, start, resume. Down: pause, stop, destroy.
Each callback marks a change of state:
| Callback | What just happened |
|---|---|
onCreate |
The activity exists. Set up the UI once. |
onStart |
It is visible. |
onResume |
It is in the foreground and receives input. |
onPause |
It is losing the foreground (maybe partly covered). |
onStop |
It is no longer visible. |
onDestroy |
It is being removed. |
When a stopped activity comes back, the system calls onRestart, then onStart and onResume again. onCreate does not repeat.
Pair your work with mirror callbacks: what you start in onStart, stop in onStop; what you start in onResume, stop in onPause.
override fun onStart() { super.onStart(); countdown.start() }
override fun onStop() { countdown.stop(); super.onStop() }