Build an Android stopwatch with lap times
A reliable lap timer should keep accurate time when the screen turns off or the user switches tasks. Australian uses include timing a coffee extraction during the arvo, a walking loop beside Melbourne’s Yarra, or intervals at a local park. The informal “give it a sec” also sets a useful UI standard: feedback should appear immediately.
Android apps reach Australian users through Google Play, where releases should be checked on different screen sizes and Android versions. The market uses Australian dollars, and users often expect 24-hour timestamps, Australian English spelling, and clear permission messages. Keep the first version local and quick rather than adding accounts or tracking it does not need.
This build uses Kotlin, XML views, and a RecyclerView. It records running time, lap splits, and a scrollable history while keeping the code approachable for a developer having a go with Android.
Plan the screen and project
Create an Empty Views Activity named StopwatchActivity and add a large TextView, three Material buttons, and a RecyclerView. Use View Binding, give the controls clear IDs such as startButton, lapButton, resetButton, and elapsedText, and place the lap history beneath the controls. Put the app in a vertical container so it scales cleanly on narrow phones and large foldables.
Let the primary button change between Start and Stop, enable Lap only while the timer runs, and make Reset clear the session. Set an accessible content description on every control, and give the time text a large, monospaced style so digits do not jump as values change. Immediate label and button-state changes prevent accidental double-starts during a quick tap.
Create a reliable timing engine
Use SystemClock.elapsedRealtime() rather than the wall clock. It is monotonic, so changing the device time or entering another time zone cannot make the timer jump. A Handler on the main looper can refresh the visible value every 50 milliseconds, while elapsed time is always recalculated from the clock.
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import java.util.Locale
private val handler = Handler(Looper.getMainLooper())
private var running = false
private var accumulated = 0L
private var startedAt = 0L
private fun elapsed(now: Long = SystemClock.elapsedRealtime()) =
if (running) accumulated + now - startedAt else accumulated
private val ticker = object : Runnable {
override fun run() {
binding.elapsedText.text = format(elapsed())
if (running) handler.postDelayed(this, 50L)
}
}
private fun format(milliseconds: Long): String {
val minutes = milliseconds / 60_000
val seconds = (milliseconds / 1_000) % 60
val hundredths = (milliseconds / 10) % 100
return "%02d:%02d.%02d".format(
Locale.US, minutes, seconds, hundredths
)
}
When Start is tapped, store startedAt; when Stop is tapped, add the current run to accumulated and remove pending callbacks. Starting again resumes from accumulated. Reset returns both values to zero, clears the laps, and leaves the app stopped.
Format the result as minutes, seconds, and hundredths with %02d:%02d.%02d. The 50-millisecond refresh is frequent enough for a centisecond display without wasteful work. Bind the three buttons to toggleTimer(), addLap(), and resetTimer(), and call updateButtons() after each action so the interface always reflects the timer state.
Record lap splits and show history
A lap split is the time since the previous split, whereas the total is the time since Start. Store both values in an immutable model, then append a new item without changing earlier laps. Reset lastLap whenever the session is cleared.
data class Lap(
val number: Int,
val splitMillis: Long,
val totalMillis: Long
)
private val laps = mutableListOf<Lap>()
private var lastLap = 0L
private fun addLap() {
val total = elapsed()
val split = total - lastLap
laps += Lap(laps.size + 1, split, total)
lastLap = total
}
Use a ListAdapter with DiffUtil to submit a copy of the list to the RecyclerView. Each row should show the lap number, split, and running total, with the newest row at the top. This keeps updates smooth when several laps are recorded and gives TalkBack a separate, meaningful label for every result.
Keep state through rotation and background use
Activity fields disappear when the configuration changes. Put running, accumulated, startedAt, and the lap list in a ViewModel so rotation does not reset the session. Add SavedStateHandle when the timer must also survive process death, but remember that reboot recovery needs a separately designed wall-clock policy.
| State approach | Rotation | Process death | Best fit |
|---|---|---|---|
| Activity fields | Lost | Lost | Throwaway prototype |
| ViewModel | Preserved | Lost | Normal short session |
ViewModel with SavedStateHandle |
Preserved | Restored | Recommended baseline |
| Foreground service | Preserved | Service-dependent | Long coaching session |
The timer need not tick while the activity is in the background: stop the callbacks if desired, then recompute elapsed() when the screen resumes. For a session that must keep running visibly in a notification, use a foreground service and follow the current foreground-service permission, notification, and service-type requirements. This is worthwhile for coached workouts but unnecessary for a normal kitchen timer.
Save results and share useful summaries
Keep the feature set small. SharedPreferences can retain the latest completed session or a favourite lap, while Room is a better fit for searchable history. Offer a plain-text or CSV export through Android’s share sheet so a runner can send results to a coach. For exported timestamps, use 24-hour time and Australian date order.
A visual coaching extension could adapt the capture video intent example to record a short training clip at a split. Treat the video as optional, store only what the user chooses, and avoid broad media permissions when the camera intent can supply the required content URI.
If the app stays local, it avoids a server and most privacy obligations. If analytics or cloud sync are added, review the Australian Privacy Act and Australian Privacy Principles, then complete Google Play’s Data safety declaration accurately. Explain camera and media access at the point of use rather than hiding it in a long onboarding flow.
Test, polish, and prepare release
Exercise the timer on a real device. Because elapsed(now) accepts a supplied time value, JUnit can verify split boundaries without waiting for the clock.
Manual checks
- Rotate the phone during a run and confirm every value survives.
- Background the app for two minutes, then check the elapsed time and lap totals.
- Tap Lap quickly, stop, resume, and reset in several different orders.
- Test large fonts, TalkBack, and small screens with long elapsed values.
Before release, build a signed Android App Bundle and use Play Console internal testing.
Release checks
- Publish an App Bundle that passes lint, unit tests, and instrumentation tests.
- Review TalkBack labels, colour contrast, touch targets, and landscape layouts.
- Declare only required permissions and complete the Data safety form.
- Test the release build on current Android versions and popular handset models in Australia.