Android SharedPreferences Tutorial and Example

Building Timer And Stopwatch Functionality In Android

A timer and stopwatch are excellent Android projects because they combine user interface design, state management, lifecycle handling and time calculations in one practical feature. A stopwatch measures elapsed time upwards, while a countdown timer starts from a chosen duration and moves towards zero.

The most reliable implementation separates timekeeping from screen updates. Android should calculate elapsed time with a monotonic clock, then refresh the display at a suitable interval. This prevents the timer from being affected when a user changes the device clock, crosses a time zone or moves between daylight-saving settings in Sydney and Melbourne.

The examples below use Kotlin and standard Android views, making them suitable for a beginner-friendly project. The same principles apply when building a study timer, gym interval tracker, cooking timer or a race-lap stopwatch for users in Brisbane, Perth or elsewhere in Australia.

Choose The Right Timing Model

A stopwatch should record the moment it starts and calculate the difference between the current elapsed time and that starting point. Android’s SystemClock.elapsedRealtime() is ideal because it measures time since the device booted and is not changed by manual clock adjustments.

A countdown timer can use CountDownTimer, which provides callbacks at regular intervals and a final callback when the duration reaches zero. For a simple screen, this is convenient. For a more flexible application, storing an end timestamp and recalculating the remaining duration gives better control during rotation, backgrounding and process recreation.

The displayed value should be treated as a presentation of the underlying state. Store milliseconds internally, then convert them into hours, minutes and seconds only when updating the TextView. This avoids rounding errors and keeps lap calculations accurate.

Build The Stopwatch Core

A straightforward stopwatch needs three states: running, paused and reset. The following Kotlin properties provide a compact starting point:

private var running = false
private var startedAt = 0L
private var accumulated = 0L
private val handler = Handler(Looper.getMainLooper())
private val tick = object : Runnable {
    override fun run() {
        if (running) {
            val elapsed = accumulated +
                (SystemClock.elapsedRealtime() - startedAt)
            timeText.text = formatDuration(elapsed)
            handler.postDelayed(this, 50L)
        }
    }
}

Starting the stopwatch records the current monotonic time. Pausing adds the current session to accumulated, while resetting clears both values. A 50-millisecond refresh feels responsive, although the display normally shows only whole seconds or hundredths.

fun startStopwatch() {
    if (!running) {
        startedAt = SystemClock.elapsedRealtime()
        running = true
        handler.post(tick)
    }
}

fun pauseStopwatch() {
    if (running) {
        accumulated += SystemClock.elapsedRealtime() - startedAt
        running = false
        handler.removeCallbacks(tick)
    }
}

A lap button can save the current elapsed value in a MutableList<Long> and show the results in a RecyclerView or ListView. For learners exploring practical coding projects, Android project examples can provide useful ideas for extending the screen with saved sessions and additional controls.

Add A Countdown Timer

For a countdown, the user can enter minutes and seconds in two EditText fields or select a duration with a NumberPicker. Validate the input before starting: reject negative values, handle empty fields safely and prevent a zero-second timer from appearing to run.

The built-in approach is concise:

private var countdown: CountDownTimer? = null

fun startCountdown(durationMillis: Long) {
    countdown?.cancel()

    countdown = object : CountDownTimer(durationMillis, 1000L) {
        override fun onTick(remaining: Long) {
            timeText.text = formatDuration(remaining)
        }

        override fun onFinish() {
            timeText.text = formatDuration(0L)
            statusText.text = "Finished"
            playAlert()
        }
    }.start()
}

playAlert() might trigger a short notification sound, vibration or a high-priority notification. Android users may have vibration disabled, so the interface should also communicate completion visually. A colour change, status label and accessible content description make the result clear without relying on audio.

For a timer expected to continue while the app is not visible, save an end time such as System.currentTimeMillis() + durationMillis. When the activity resumes, subtract the current wall-clock time from that end value. A foreground service or notification may be appropriate for longer-running tasks, subject to modern Android background execution rules.

Design A Clear Timer Interface

Place the time display prominently at the top of the layout, followed by primary actions such as Start, Pause, Reset and Lap. Use a ConstraintLayout or a vertical LinearLayout with generous spacing so controls remain usable on small phones. Large touch targets are particularly helpful when someone is cooking or timing exercise.

Use meaningful labels instead of relying on icons alone. A button labelled “Pause” is easier to understand than a symbol, while a separate “Reset” action should require deliberate interaction to prevent accidental data loss. Update button text and enabled states as the timer changes state.

The time formatter can produce either MM:SS or HH:MM:SS:

fun formatDuration(milliseconds: Long): String {
    val totalSeconds = milliseconds / 1000
    val seconds = totalSeconds % 60
    val minutes = (totalSeconds / 60) % 60
    val hours = totalSeconds / 3600

    return if (hours > 0) {
        "%02d:%02d:%02d".format(hours, minutes, seconds)
    } else {
        "%02d:%02d".format(minutes, seconds)
    }
}

Test the layout with large font settings and TalkBack enabled. Australian users access Android through a wide range of affordable and premium devices sold locally, so avoid assuming a particular screen size or refresh rate.

Protect State During Lifecycle Changes

An activity can be recreated when the device rotates, when the language changes or when Android reclaims resources. Storing the live timer only in view fields means the display may reset unexpectedly. Use a ViewModel for active state and SavedStateHandle for small values such as the running flag, start timestamp and accumulated duration.

When the app is paused, stop unnecessary display callbacks rather than allowing a hidden activity to update its views. On resume, calculate the correct value again and restart the refresh loop if the timer is still active. This keeps the interface efficient and reduces battery use.

Do not use the local wall clock to measure elapsed stopwatch time. Daylight-saving changes in New South Wales, Victoria and Tasmania can alter the displayed civil time, while Queensland does not observe daylight saving. A stopwatch should remain accurate regardless of those regional differences. Wall-clock timestamps are useful for scheduling and persistence; monotonic time is better for measuring duration.

Compare Implementation Approaches

The best option depends on how long the timer must run, whether it needs background support and how much control the application requires.

Requirement Suitable Android approach Main advantage Important consideration
Basic visible stopwatch Handler with elapsedRealtime() Simple and easy to learn Stop callbacks when the screen is inactive
Short countdown on screen CountDownTimer Concise tick and finish callbacks Recreate or restore it after lifecycle changes
Persistent countdown Saved end timestamp Remains accurate after pauses Recalculate remaining time on resume
Background timing Foreground service and notification Works beyond the activity Requires notification and background-policy handling
Lap or session history RecyclerView with a data model Scales to many records Save records if they must survive app closure

Testing should cover start, pause, resume, reset, rotation, backgrounding and rapid button presses. Also test a countdown that reaches zero while the screen is locked. If the app is intended for Australian users, verify notification behaviour under local device settings and check that times do not depend on the phone’s selected city or time zone.

Recommendations For A Reliable Timer

Keep the timing engine independent from the activity and let the activity render its current state. This makes the feature easier to test and allows the same logic to support a stopwatch tab, a countdown tab and interval training. A small state model can include IDLE, RUNNING, PAUSED and FINISHED, preventing invalid combinations such as a paused timer with no stored start value.

Use these implementation practices:

  • Measure stopwatch duration with SystemClock.elapsedRealtime().
  • Store countdown end times when the timer must survive background activity.
  • Cancel callbacks and CountDownTimer objects when they are no longer needed.
  • Persist important values with a ViewModel, SavedStateHandle or a small local database.
  • Provide visual, audible and vibration feedback when a countdown finishes.

A polished Android timer is more than a changing number. It should preserve state, communicate its status clearly and behave consistently across devices, screen sizes and Australian time-zone settings. With those foundations in place, features such as interval presets, lap exports and notification controls can be added without rewriting the timing logic.