Android SharedPreferences Tutorial and Example

Developing a stopwatch with Timer and Chronometer

Many Android apps need a dependable elapsed-time display for exercise intervals, kitchen timers or connection windows. A stopwatch is also a compact lesson in UI state, monotonic time and lifecycle-aware Kotlin.

This build uses Android’s Chronometer for the running display and start, stop and reset buttons. It also shows where Timer, CountDownTimer and delayed messages belong while keeping the measured duration independent of the device’s wall clock.

Define the behaviour before coding

Create an Empty Views Activity in Android Studio, select Kotlin and choose a minimum SDK that suits your audience. Enable view binding, then place a Chronometer in the centre of a vertical layout with three buttons beneath it. Give the timer and each button stable IDs so the activity code remains clear.

Decide what happens after Stop and after the screen rotates. The app needs only two pieces of logical state: accumulated time and a running flag. Keep presentation separate from timing so a rotation can rebuild the interface without resetting the measurement.

A useful local scenario is a Sydney or Melbourne commuter checking the time between a train, tram or ferry connection. Melbourne cafés also use short timers for espresso extraction, while home cooks may time resting dough. These habits favour a large, legible readout and immediate pause control.

Build the Chronometer interface

In the layout, set the Chronometer text size to roughly 48sp and give it an accessibility label such as “Elapsed time”. Use IDs named chronometer, startButton, stopButton and resetButton, with string resources for the button captions.

Format the value as minutes, seconds and tenths, adding hours only for longer sessions. Wire the controls in the activity with the essential timing operations:

private var accumulatedMs = 0L
private var running = false

private fun startStopwatch() {
    if (running) return

    binding.chronometer.base =
        SystemClock.elapsedRealtime() - accumulatedMs
    binding.chronometer.start()
    running = true
}

private fun stopStopwatch() {
    if (!running) return

    binding.chronometer.stop()
    accumulatedMs =
        SystemClock.elapsedRealtime() - binding.chronometer.base
    running = false
}

Reset should stop the Chronometer, clear accumulatedMs and set running to false. Register an OnChronometerTickListener to pass each elapsed value to your formatter. Calculate that value from SystemClock.elapsedRealtime() when a custom timer supplies updates, and format with Locale.getDefault() so separators and numerals suit the user’s settings.

Compare timer mechanisms

Choose the mechanism by the job it performs. A stopwatch measures elapsed duration, a countdown tracks remaining time, and a scheduler periodically requests another update. These jobs overlap, but their lifecycle and precision differ.

Mechanism Best fit Behaviour Main caution
Chronometer Live elapsed display Ticks against monotonic time Rebuild its state after recreation
CountDownTimer Fixed remaining duration Usually updates about once per second Too coarse for tenths
Handler.postDelayed Short UI or background message Runs on the selected looper Delay is not an exact timer
Timer or ScheduledExecutorService Repeated scheduled work Uses a worker thread Cancel it and marshal UI updates

Chronometer is the natural Android view for this project because it already follows elapsedRealtime and exposes tick callbacks. CountDownTimer is designed for a known remaining duration and normally reports at roughly one-second intervals, making it a poor source for tenths-of-a-second display values.

java.util.Timer can schedule fixed-rate work on a worker thread, but its callback must post UI changes to the main thread. Treat that callback as a redraw signal rather than the source of truth, cancel the timer when its scope ends and create a new instance after cancellation. For new background work, ScheduledExecutorService usually offers clearer lifecycle control.

Preserve state across lifecycle changes

Android may destroy and recreate an Activity during rotation, while background limits can suspend callbacks. Save accumulated time and the running flag in a ViewModel or SavedStateHandle. When restoring a running stopwatch, rebuild the Chronometer base from SystemClock.elapsedRealtime(). This preserves the duration across configuration changes without relying on a background thread.

Keep elapsed time separate from calendar time. elapsedRealtime is monotonic and continues through deep sleep, whereas currentTimeMillis can move when the network corrects the clock. Australian timetables often use 24-hour notation. Daylight saving also changes in Sydney, Melbourne, Adelaide and Canberra, while Brisbane keeps standard time, so a countdown tied to a local appointment should use an IANA time zone and be recalculated after a clock change.

SharedPreferences can hold a preferred unit or saved mode, but keep personal or sensitive timing data out of logs. If the app collects analytics, account identifiers or location, document its purpose and handling before release. Local preferences alone generally carry less risk than transmitting a user’s activity history.

Verify behaviour and prepare the release

Test on several Android versions and on handsets sold in the Australian market, including representative Google, Samsung and Motorola models. Google Play is the principal Android storefront here, so the release bundle, permission declaration and Data safety form should be checked alongside device behaviour.

Functional checks:

  • Start, stop, resume and reset the stopwatch, then verify every displayed digit.
  • Rotate the screen during a run and confirm the value continues.
  • Leave the app backgrounded for 30 seconds, return and compare the result with elapsedRealtime.
  • Tap the controls rapidly and run the stopwatch beyond one hour.

Release checks:

  • Use 48dp touch targets, visible focus, TalkBack labels and no colour-only status.
  • Build a signed Android App Bundle and test installation and updates.
  • Match the Play Store Data safety form and privacy policy to actual data handling.
  • Confirm that the app does not request unnecessary background or location permissions.

For a commercial app, review the Privacy Act 1988 and Australian Privacy Principles when personal information is handled; the Privacy Act’s coverage depends on the organisation and data involved. The Australian Consumer Law, contained in the Competition and Consumer Act 2010, also governs claims about accuracy and refunds. Advertising a stopwatch as “lap accurate” should match its behaviour during sleep, rotation and background use.