Android SharedPreferences Tutorial and Example

Build a practical Android countdown timer

Building an Android countdown timer combines interface design, time calculation, background execution and notification handling. A useful version is more than a TextView changing every second: it must maintain the correct remaining time after rotation, screen locking or a temporary trip to another app. Kotlin, ViewModel and coroutines provide a maintainable foundation for these requirements.

The app should work offline because Australian households commonly use timers during barbecues, camping trips and busy sporting events where reception may be unreliable. For the Australian market, use Australian English in resources and monitor feedback from Australian Google Play users. These constraints turn a simple tutorial project into an application suitable for everyday use.

Define the timer’s behaviour and states

Start with a compact state model containing idle, running, paused and finished states. Store the selected duration and remaining milliseconds in one source of truth, then let the interface render that state. This prevents a screen rotation from resetting the countdown and makes it easier to implement start, pause, resume and reset actions without contradictory button states.

Keep elapsed timing separate from civil time. Daylight saving changes and the distance between Perth, Adelaide, Brisbane, Sydney and Melbourne must not shorten or extend a running countdown. If the app displays an estimated finish time, offer familiar 24-hour Australian notation such as 18:30 while keeping the main readout in minutes and seconds.

Set up the project and duration input

Create an Android Studio project with Kotlin, XML layouts and View Binding, then add the lifecycle, activity and coroutine dependencies required by your chosen architecture. A single-activity structure is sufficient for the main timer screen. Give the activity a ViewModel so that configuration changes do not restart the countdown or require the timer logic to live in the activity.

Accept a positive number of minutes, optionally combined with seconds, and convert the input into milliseconds before starting the coroutine. Reject zero, negative and excessively long values with an inline error message. Users normally choose a duration, but an optional countdown-to-event mode can accept a calendar date. The date picker dialog example demonstrates opening a DatePickerDialog from an EditText click; convert the selected date into a target timestamp and calculate the difference from the current time.

Create an accessible countdown screen

Use a TextView for the remaining time, a CircularProgressIndicator for visual feedback and clearly labelled MaterialButtons for the available actions. Keep the layout compact enough for a phone held in one hand, while allowing the remaining time to remain readable in landscape mode. Format values with Locale.getDefault() so text and numerals follow the device’s regional conventions.

Update the display at a measured interval rather than requesting thousands of frames per second. A quarter-second tick can support a circular progress indicator smoothly, while a one-second tick is sufficient when only the text changes. Provide accessible labels for icon-only controls, maintain comfortable touch targets and avoid communicating status through colour alone. Announce important milestones such as the final ten seconds rather than forcing a screen reader to repeat every tick.

Choose timing logic that survives lifecycle changes

The main implementation choices have different strengths, so select one according to how long the countdown may run and whether it must operate in the background.

Approach Best fit Main benefit Main limitation
CountDownTimer Short, simple in-app countdowns Compact API with regular tick callbacks Does not restore state by itself
ViewModel and elapsedRealtime() Most single-screen timers Lifecycle-aware and easy to test Requires explicit state restoration
Foreground service Long countdowns running in the background Keeps an ongoing notification visible Adds permissions and implementation complexity

For a typical countdown, use a ViewModel with coroutines and calculate the deadline using SystemClock.elapsedRealtime(). Derive the remaining duration from that deadline whenever the screen resumes instead of assuming every elapsed second produced exactly one callback. Save the relevant state in SavedStateHandle for process recreation, and store a wall-clock target as well if restoration after a device reboot matters. A foreground service becomes appropriate when a reliable background alert is required for a long-running timer.

Deliver completion alerts and local settings

Create a notification channel when the app is installed or first launched, request notification permission on Android 13 and later, and provide an in-app completion state even when notifications are denied. A short timer can show an alert when the user returns to the app, whereas a long timer may need a foreground service. Test notification behaviour with the channel disabled, permission denied and Do Not Disturb active rather than assuming the default device settings.

Offer vibration, sound and duration-preset options without overriding the phone’s silent mode. Australian users might set a timer for a Melbourne Cup lunch, an AFL match, a school carnival or a long barbecue, so the completion signal should be noticeable without becoming intrusive. Avoid keeping the screen awake unless the user explicitly enables that behaviour, and stop any active service as soon as the timer is reset or cancelled.

Recommendations for testing and release

Exercise the countdown under realistic interruptions, including rotation, split-screen use, backgrounding, screen-off periods, process recreation and device reboot. Automated tests can verify deadline calculations, while instrumentation tests should confirm that controls and notifications behave correctly on an emulator or physical device.

Before publishing, check the timer against compact and large screens, Android’s current notification rules and Australian English resources. A staged release and Android vitals monitoring can expose lifecycle or battery problems that appear only after the app reaches real devices.

  • Test rapid repeated taps to ensure the timer cannot be started twice.
  • Verify pause, resume, reset and cancellation while the screen is locked.
  • Check duration boundaries, including zero, one second and unusually long values.
  • Test notification permission denial, muted channels and Do Not Disturb.
  • Include Australian time formats, English resources and daylight-saving scenarios.
  • Publish gradually, monitor Australian Play Store feedback and release prompt fixes.