Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester

Week 13 Lab 13 – Build a Countdown Timer App

Week 13 – Web Services: Accessing and Creating · 150 min read · 8 MCQs to check yourself

Coding in Flow – Countdown timer with Start, Pause and Reset (Java)

Coding in Flow – Countdown timer part 2: orientation changes (Java)

Objective

Build a Quiz Timer with Android's CountDownTimer class: show MM:SS, Start / Pause / Reset, vibrate at the end, and keep the correct time when the phone is rotated. CLOs: CLO-2 (develop apps with timed tasks), CLO-3 (lifecycle and performance – cancel timers, save state).

What you will build in CampusMate

QuizTimerActivity – a 1-minute timer for a class quiz:

Control Action
01:00 text Shows the time left
Start Starts (or resumes) counting down
Pause Stops and remembers the time left
Reset Back to 01:00
At 00:00 "Time's up!" + short vibration

Workflow

Step What you do File
1 Create the activity and add the VIBRATE permission New → Activity, manifest
2 Design the screen activity_quiz_timer.xml
3 Variables and updateText() QuizTimerActivity.java
4 Start with CountDownTimer (onTick / onFinish) startTimer()
5 Pause and Reset pauseTimer(), resetTimer()
6 Save and restore on rotation onSaveInstanceState()
7 Cancel in onDestroy onDestroy()
8 Run and test Emulator

Step 1 – Activity and permission

New → Activity → Empty Views Activity → QuizTimerActivity (Java). Manifest, above <application>:

<uses-permission android:name="android.permission.VIBRATE" />

(VIBRATE is a normal permission – granted at install, no dialog.)

Step 2 – Layout (activity_quiz_timer.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="24dp">

    <TextView
        android:id="@+id/tvTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="01:00"
        android:textSize="64sp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button android:id="@+id/btnStart"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Start" />

        <Button android:id="@+id/btnPause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Pause" />

        <Button android:id="@+id/btnReset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Reset" />
    </LinearLayout>
</LinearLayout>

Step 3 – Variables and showing MM:SS

package com.example.campusmate;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.os.Build;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Locale;

public class QuizTimerActivity extends AppCompatActivity {

    private static final long START_MS = 60_000;    // 1 minute

    private TextView tvTime;
    private CountDownTimer timer;                   // null when not running
    private long remainingMs = START_MS;            // time left
    private boolean running = false;
    private long endTime;                           // clock time when the timer will finish

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz_timer);

        tvTime = findViewById(R.id.tvTime);
        findViewById(R.id.btnStart).setOnClickListener(v -> startTimer());
        findViewById(R.id.btnPause).setOnClickListener(v -> pauseTimer());
        findViewById(R.id.btnReset).setOnClickListener(v -> resetTimer());

        // Step 6 restore code goes here
        updateText();
    }

    private void updateText() {
        int minutes = (int) (remainingMs / 1000) / 60;
        int seconds = (int) (remainingMs / 1000) % 60;
        tvTime.setText(String.format(Locale.US, "%02d:%02d", minutes, seconds)); // 01:05, not 1:5
    }
}

Step 4 – Start: the CountDownTimer

private void startTimer() {
    if (running) return;                              // do not start two timers
    endTime = SystemClock.elapsedRealtime() + remainingMs;

    //                      millisInFuture, countDownInterval
    timer = new CountDownTimer(remainingMs, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {   // every 1 second
            remainingMs = millisUntilFinished;
            updateText();
        }

        @Override
        public void onFinish() {                         // once, at the end
            running = false;
            remainingMs = 0;
            updateText();
            Toast.makeText(QuizTimerActivity.this, "Time's up!", Toast.LENGTH_SHORT).show();
            vibrate();
        }
    }.start();
    running = true;
}

private void vibrate() {
    Vibrator v = getSystemService(Vibrator.class);
    if (v == null) return;
    if (Build.VERSION.SDK_INT >= 26) v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
    else v.vibrate(500);
}
Parameter / method Meaning
millisInFuture Total time (here the remaining time)
countDownInterval How often onTick runs (1000 ms = every second)
onTick(ms) Called every interval with the time left
onFinish() Called once when the time reaches zero

Step 5 – Pause and reset

private void pauseTimer() {
    if (timer != null) timer.cancel();   // CountDownTimer has no pause – cancel and keep remainingMs
    running = false;
}

private void resetTimer() {
    pauseTimer();
    remainingMs = START_MS;
    updateText();
}

Pause = cancel + remember the time left; Start then creates a new timer from remainingMs.

Step 6 – Keep the correct time on rotation

Rotation destroys the activity (and its timer). Save the state:

@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putLong("remaining", remainingMs);
    outState.putBoolean("running", running);
    outState.putLong("endTime", endTime);
}

Restore it in onCreate (replace the comment from Step 3):

if (savedInstanceState != null) {
    remainingMs = savedInstanceState.getLong("remaining", START_MS);
    boolean wasRunning = savedInstanceState.getBoolean("running", false);
    if (wasRunning) {
        endTime = savedInstanceState.getLong("endTime");
        remainingMs = endTime - SystemClock.elapsedRealtime();  // time also passed during rotation
        if (remainingMs > 0) startTimer();
        else remainingMs = 0;
    }
}

Saving the end time (not just the remaining time) keeps the timer exact even though the rotation itself takes a moment. A ViewModel (theory week 14) is another way to keep data across rotation.

Step 7 – Stop the timer when the screen closes

@Override
protected void onDestroy() {
    if (timer != null) timer.cancel();   // otherwise it keeps ticking and leaks the old activity
    super.onDestroy();
}

Run and test

Test Expected result
Start 01:00 → 00:59 → 00:58 …
Pause at 00:40, wait, Start Continues from 00:40
Reset 01:00, stopped
Rotate while running (Ctrl+←) Keeps counting from the correct time
Rotate while paused Same paused time
Reach 00:00 "Time's up!" and vibration (on a phone)
Press Start twice Only one timer (no double-speed)

Common errors and fixes

Problem Fix
Time runs twice as fast Two timers – check if (running) return;
Shows 1:5 Use String.format(Locale.US, "%02d:%02d", …)
Timer resets to 01:00 after rotation Save and restore in onSaveInstanceState (Step 6)
SecurityException on vibrate Add the VIBRATE permission

Short and long questions

1. (Viva) Explain the CountDownTimer class and its methods.

Model answer

CountDownTimer(millisInFuture, countDownInterval) counts down on the main thread; onTick(millisUntilFinished) is called every interval to update the UI and onFinish() once at the end; start() begins and cancel() stops it.

2. (Viva) How did you implement pause and resume?

Model answer

Pause cancels the running timer and keeps remainingMs from the last onTick; Resume creates a new CountDownTimer with remainingMs and starts it. Reset cancels the timer and sets the remaining and total time to zero.

3. (Viva) How did your timer survive rotation?

Model answer

onSaveInstanceState stored total time, remaining time, running flag and the absolute end time; after recreation onCreate read them, recomputed remaining = endTime − now and started a new timer if it was running. The old timer was cancelled in onDestroy.

This lesson ends with a quiz of 8 MCQs. Open the lesson on PrepOasis to take it and save your progress.

Previous: Week 13 Theory – Web Services – Accessing and Creating · Next: Assignment 3 (Weeks 10–13) – Course Notes and Announcements: Data, REST API and Messaging

All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester