Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 104 ยท Building a Real UI

Timers, Clocks, Sensors and Speech in Android

Build time and device-feature screens on Android: CountDownTimer, Chronometer, stopwatch logic, analog and digital clocks, CalendarView, step counter and shake sensors, speech recognition and text to speech.

A lot of small Android apps are built from the same handful of device features: a countdown or stopwatch, a clock, a calendar, motion sensors (steps, shake), and voice (speech in, speech out). They share one skill: time and events arrive on their own schedule, and your UI must stay correct while they do. This lesson covers the classic View-system classes (CountDownTimer, Chronometer, AnalogClock/TextClock, CalendarView), the Compose equivalents, then sensors and the two speech APIs.

None of these can run on this site, so the Android code is read-only. The TryIts are plain Kotlin and test the logic that is yours: formatting, state machines and signal processing. Related lessons: Side effects in Compose for timers inside composables, Date and time pickers for picking a date, and Permissions for the sensor and microphone permissions below.

CountDownTimer

CountDownTimer(millisInFuture, countDownInterval) calls onTick repeatedly and onFinish once. It runs on the main thread's Handler, so you can update views directly.

Kotlin
// read-only example: a 30-second countdown
private var timer: CountDownTimer? = null

private fun startTimer() {
    timer?.cancel()                                    // never leave two timers running
    timer = object : CountDownTimer(30_000, 1_000) {
        override fun onTick(millisUntilFinished: Long) {
            binding.time.text = "${millisUntilFinished / 1000}"
        }
        override fun onFinish() {
            binding.time.text = "Done"
        }
    }.start()
}

override fun onDestroy() {
    timer?.cancel()                                    // otherwise it keeps a reference to the Activity
    super.onDestroy()
}

The timer dies with the process and does not survive rotation unless you hold it in a ViewModel (see ViewModel). In Compose, the usual replacement is a LaunchedEffect with delay, or better, a Flow from the ViewModel:

Kotlin
// read-only example: a countdown as a Flow
fun countdown(seconds: Int): Flow<Int> = flow {
    for (s in seconds downTo 0) {
        emit(s)
        delay(1_000)
    }
}

Both approaches have drift: delay(1000) and the timer's tick interval are not exact, and ticks stop when the app is paused. For a timer that must be right after the app was in the background, store the end time (System.currentTimeMillis() + duration) and compute the remaining time from it, instead of counting ticks.

Kotlin Countdown from an end time (no drift)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Chronometer and stopwatch logic

Chronometer is a TextView that counts up by itself: set base = SystemClock.elapsedRealtime(), call start() and stop(). For a real stopwatch with Start, Stop and Reset you also need to keep the elapsed time while stopped and continue from it. The state machine is the part worth testing:

Kotlin
// read-only example: Chronometer with pause and resume
private var pausedAt = 0L

fun start() {
    binding.chrono.base = SystemClock.elapsedRealtime() - pausedAt   // continue from where we stopped
    binding.chrono.start()
}
fun stop() {
    pausedAt = SystemClock.elapsedRealtime() - binding.chrono.base
    binding.chrono.stop()
}
fun reset() {
    pausedAt = 0
    binding.chrono.base = SystemClock.elapsedRealtime()
    binding.chrono.stop()
}

Use SystemClock.elapsedRealtime() (monotonic, unaffected by the user changing the clock) for durations, and System.currentTimeMillis() only for wall-clock moments.

A hand-made stopwatch that posts a Runnable to a Handler every 100 ms has the same issue as the countdown: compute from timestamps, do not add up ticks.

Kotlin Stopwatch state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Clocks and calendars

  • TextClock is the modern digital clock TextView: android:format12Hour="hh:mm a" and android:format24Hour="HH:mm". It updates itself and follows the device time zone.
  • AnalogClock draws hands but is deprecated in recent API levels; use a custom Canvas drawing or a Compose Canvas for new work. The hand angles are simple arithmetic.
  • CalendarView shows a month grid; listen with setOnDateChangeListener { view, year, month, day -> ... }. Note that month is 0-based (January is 0), a classic bug. For a modern, themed picker use Material's date picker (see Date and time pickers).

The analog-clock math is worth seeing once: the minute hand moves 6 degrees per minute, the hour hand 30 degrees per hour plus 0.5 degrees per minute.

Kotlin Clock hand angles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Sensors

Android devices expose motion and environment sensors through SensorManager. You register a SensorEventListener for a sensor type and receive onSensorChanged with a values array.

Kotlin
// read-only example: listen to the accelerometer
class MotionActivity : AppCompatActivity(), SensorEventListener {
    private lateinit var sensors: SensorManager
    private var accelerometer: Sensor? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        sensors = getSystemService(SENSOR_SERVICE) as SensorManager
        accelerometer = sensors.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)   // null if the device lacks it
    }

    override fun onResume() {
        super.onResume()
        accelerometer?.also { sensors.registerListener(this, it, SensorManager.SENSOR_DELAY_UI) }
    }

    override fun onPause() {
        super.onPause()
        sensors.unregisterListener(this)         // sensors drain the battery: always unregister
    }

    override fun onSensorChanged(event: SensorEvent) {
        val (x, y, z) = event.values            // m/s^2 including gravity (about 9.81 when still)
    }
    override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) = Unit
}

Common sensor types: TYPE_ACCELEROMETER, TYPE_GYROSCOPE, TYPE_LIGHT, TYPE_PROXIMITY, TYPE_STEP_COUNTER and TYPE_STEP_DETECTOR. Declare optional hardware with <uses-feature android:name="android.hardware.sensor.stepcounter" android:required="false" /> and check at run time.

Step counting

The easiest step counter uses the hardware TYPE_STEP_COUNTER, which reports the total steps since the last reboot. Reading it needs the ACTIVITY_RECOGNITION runtime permission (API 29+). Because the value only grows until a reboot, you store a baseline and show current - baseline:

Kotlin
// read-only example: today's steps from a cumulative counter
override fun onSensorChanged(event: SensorEvent) {
    val total = event.values[0].toLong()
    if (baseline < 0) baseline = prefs.getLong("baseline", total).also { prefs.edit().putLong("baseline", it).apply() }
    binding.steps.text = (total - baseline).toString()
}

Detecting a shake (from raw samples)

Many "shake to undo" or Magic 8 Ball apps compute a shake from accelerometer samples. A signal that stays near gravity (9.8) is still; a strong spike is a shake. Filter by magnitude and add a cooldown so one shake does not fire ten times.

Kotlin Shake detection from accelerometer samples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Speech: recognition and synthesis

Speech to text has two routes. The easy route is an Intent with RecognizerIntent.ACTION_RECOGNIZE_SPEECH: the system shows its own dialog and returns the result in onActivityResult (or an Activity Result API launcher). The controllable route is SpeechRecognizer, which needs the RECORD_AUDIO permission and reports partial and final results through a RecognitionListener.

Kotlin
// read-only example: system speech dialog with the Activity Result API
private val speechLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    val text = result.data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)?.firstOrNull()
    if (text != null) binding.input.setText(text)
}

private fun listen() {
    val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
        putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
        putExtra(RecognizerIntent.EXTRA_PROMPT, "Say your note")
    }
    speechLauncher.launch(intent)
}

Text to speech is TextToSpeech: construct it with an OnInitListener, set the language after init succeeds, call speak, and shut it down in onDestroy.

Kotlin
// read-only example
private lateinit var tts: TextToSpeech

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    tts = TextToSpeech(this) { status ->
        if (status == TextToSpeech.SUCCESS) tts.language = Locale.US
    }
}
fun say(text: String) { tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, "msg-1") }

override fun onDestroy() { tts.stop(); tts.shutdown(); super.onDestroy() }

Voice features help users who cannot read or type easily (see Accessibility), but they also need honest handling of errors: no recognizer installed, no network on some devices, permission denied and "no match" are all normal.

Common mistakes

  • Starting a new CountDownTimer without cancelling the old one: the display flickers between two timers.
  • Counting ticks instead of using timestamps, so the time is wrong after the app was paused.
  • Forgetting unregisterListener, which drains the battery.
  • Assuming a sensor exists. getDefaultSensor returns null on devices without it.
  • Treating CalendarView's month as 1-based.
  • Not releasing TextToSpeech or SpeechRecognizer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is it better to compute a countdown from an end time than to count ticks?

    Remaining time = end time minus now, so it is right even if the app was in the background or ticks were late.
  2. 2. What does TYPE_STEP_COUNTER report?

    The value only grows until reboot, so you store a baseline and subtract it. It also needs the ACTIVITY_RECOGNITION permission.
  3. 3. What should you do in onPause when you registered a SensorEventListener in onResume?

    Registered sensors keep the hardware active and drain the battery. Pair register and unregister with the lifecycle.
  4. 4. In CalendarView's date-change callback, what is the value of month for January?

    Months are 0-based in this callback, a common source of off-by-one bugs.

Summary

  • CountDownTimer, Chronometer and handler loops tick on the main thread; cancel them and prefer timestamps over tick counting.
  • A stopwatch is a small state machine of accumulated time plus a running start.
  • TextClock and Material pickers replace the old analog clock and calendar widgets; remember 0-based months.
  • Register sensors in onResume, unregister in onPause, check for null, and use a baseline for the step counter.
  • Speech in uses RecognizerIntent or SpeechRecognizer; speech out uses TextToSpeech, which you must shut down.

Next: Ads in Android apps.