Tutorial

Android CountDownTimer Example

Published on August 3, 2022
Default avatar

By Anupam Chugh

Android CountDownTimer Example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

In this android countdown timer example, we’ll implement a timer object to display the progress in a ProgressBar. The application we’ll build in this tutorial is a useful component in Quiz apps where the time left to complete the level is displayed graphically to enhance the user experience.

Android CountDownTimer

Android CountDownTimer class is used to schedule a countdown until a time in the future defined by the user, with regular notifications on intervals along the way. This class is an abstract class whose methods need to be overridden to implement it in our project. The following line needs to be added in our activity to import the class : import android.os.CountDownTimer; The relevant methods of the CountDownTimer Class are given below.

  1. synchronized final void cancel() : This is used to cancel the countdown
  2. abstract void onFinish() : This callback method is fired when the timer finishes
  3. abstract void onTick(long millisUntilFinished) : This callback method is fired on regular intervals
  4. synchronized final CountDownTimer start() : This method is used to start the countdown

The signature of the public constructor of the CountDownTimer class is given below. CountDownTimer(long millisInFuture, long countDownInterval) The parameters of the constructors are defined as follows :

  • millisInFuture : The number of milli seconds in the future from the call to start() until the countdown is done and onFinish() is called
  • countDownInterval : The interval along the way to receive onTick(long) callbacks

In this project we’ll update the time values in a ProgressBar as the onTick() method is invoked repeatedly.

Android Countdown Timer Example Project Structure

android countdown timer example project

Android Countdown Timer Code

The activity_main.xml consists of two buttons i.e. the start and stop timer buttons and a ProgressBar to display the time. activity_main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:minHeight="50dp"
        android:minWidth="200dp"
        android:progress="0"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Timer"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="61dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Timer"
        android:id="@+id/button2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="46dp"
        android:layout_below="@+id/progressBar" />

</RelativeLayout>

The MainActivity.java is given below :

package com.journaldev.countdowntimer;

import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    ProgressBar progressBar;
    Button start_timer,stop_timer;
    MyCountDownTimer myCountDownTimer;

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

        progressBar=(ProgressBar)findViewById(R.id.progressBar);
        start_timer=(Button)findViewById(R.id.button);
        stop_timer=(Button)findViewById(R.id.button2);

        start_timer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                myCountDownTimer = new MyCountDownTimer(10000, 1000);
                myCountDownTimer.start();

            }
        });

        stop_timer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                myCountDownTimer.cancel();

            }
        });

    }

    public class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {

            int progress = (int) (millisUntilFinished/1000);

            progressBar.setProgress(progressBar.getMax()-progress);
        }

        @Override
        public void onFinish() {
            finish();
        }
    }
}

In the above code we’ve defined an Anonymous Inner Class called MyCountDownTimer. In this example we’ve set a Timer for 10 seconds that updates after every second. By default the timer displays/updates the time in decreasing order ( as its named CountDown!), Hence to show the progress in increasing order we’ve subtracted the time from the max time. The timer once stopped restarts from the beginning. Below is our android countdown timer app in action. android countdowntimer example This brings an end to countdown timer android tutorial. You can download the final Android CountDownTimer Project from the below link.

Download Android CountDownTimer with ProgressBar Project

Reference: Official Documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Anupam Chugh

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 25, 2018

It donot update the last second ??? why

- Shantanu more

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    April 30, 2018

    Thank you so much for your blog. I have learn so much. One question about the follow. “In the above code we’ve defined an Anonymous Inner Class called MyCountDownTimer” Wouldn’t the class not be Anonymous if it has a name?

    - Joseph Werns

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 13, 2017

      Using non static inner class will leak your memory.

      - Long Luong

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        January 19, 2017

        after finishing the progress bar why apps is closing?

        - julfikar

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          July 26, 2016

          Thanks!

          - Camilo Fernando

            Try DigitalOcean for free

            Click below to sign up and get $200 of credit to try our products over 60 days!

            Sign up

            Join the Tech Talk
            Success! Thank you! Please check your email for further details.

            Please complete your information!

            Get our biweekly newsletter

            Sign up for Infrastructure as a Newsletter.

            Hollie's Hub for Good

            Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

            Become a contributor

            Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

            Welcome to the developer cloud

            DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

            Learn more
            DigitalOcean Cloud Control Panel