Engineering
Digital Generation
1 min read
Why a timer should not count down
Writing a reliable timer on Android means storing a timestamp, not decrementing a counter.
The most common mistake when writing a timer is counting backwards. When the app is backgrounded, or the system suspends or kills the process, the counter stops and the user sees the wrong time.
The right approach: store the end instant
You store not the counter but the instant the session ends. Every time the screen opens, the remaining time is computed from that instant. Even if the process is killed, the arithmetic is still right.
A timer is not a state. It is a calculation.
The reboot problem
On reboot elapsedRealtime resets. To catch this, the boot counter is stored alongside; if it changed, the record is treated as stale.