Android Count Down Timer Tutorial


A countdown is a sequence of backward counting to indicate the time remaining before an event is scheduled to occur. To achieve countdown Android comes with a built-in CountDownTimer class for constructing CountDownTimers. Its easy to use, efficient and works.This class is an abstract class whose methods need to be overridden to implement it in our project.

Let’s Get it Working

In this tutorial we are going to learn the basic usage of CountDownTimer. To really understand the usage of count down timer we will create an app. This app show the circular progress bar , time and start/stop image to control the count down timer.

Count Down Timer App

Count Down Timer App

DownloadCode
 
github

Basic Usage

Implementing a Count Down Timer in your app won’t take more than two steps. First you need to create an object of in-built abstract class named CountDownTimer. This class is used to Schedule a countdown until a time in the future, with regular notifications on intervals along the way.

Second you have to start the count down timer via invoking start() method.

Step 1) Creating New Project

Create a new project in Android Studio from File ⇒ New Project Fill the required information like project name and package name of the project. When it prompts you to select the default activity, select Empty Activity and proceed.

Step 2) Defining strings,colors and styles

2.1 Add the below string values to the strings.xml located in res ⇒ values ⇒ strings.xml.

2.2 Add the below color values to the colors.xml located in res ⇒ values ⇒ colors.xml.

2.3 Add the below style values to the styles.xml located in res ⇒ values ⇒ styles.xml.

Step 3) Adding drawable

Before creating layout we have to write custom drawable xmls for circular progress bar .And also need some images for start, stop and reset icon.
3.1 Create new drawable resource file by right click on drawable ⇒ New ⇒ Drawable resource file name it drawable_circle_yellow.xml and add the below code to it. This file will create a yellow hollow circle of 10dp of thicknes.

3.2 Again Create new drawable resource file by right click on drawable ⇒ New ⇒ Drawable resource file name it drawable_circle_dark_blue.xml and add the below code to it. This file will create a blue hollow circle of 10dp of thicknes.

3.3 Download the images zip. Unzip it and place all the images in drawable folder.

Step 4) Creating the layout

Now add the below code to activity_main.xml located in res ⇒ layout ⇒ activity_main.xml. This code will create a view show above in the screen shot i.e a circular progress bar to show the time elapsed progress, input field to enter minutes, text field to show the time, start/stop and reset image to control the count down timer.





Step 5) Writing Code in MainActivity class

Now add the below code to MainActivity.java located in java ⇒ project’s package ⇒ MainActivity. Here i have written code to initialize views, added click listeners on it ,methods to control start stop reset functionality.

initViews() to intialize views.
initListeners() to initialize the click listeners.
setTimerValues() fetches the input minute value from the edit text, convert minutes to milliseconds that is required for count down timer.
startCountDownTimer() initializes the abstract class count down timer object with two implemented methods onTick(long milliSeconds) and onFinish(). onTick(long milliSeconds) Callback is fired on regular interval and onFinish() Callback is fired when the time is up. With count down timer object i started it by calling countDownTimer.start();
stopCountDownTimer() stops the count down timer by calling cancel() method.
startStop() contains start/stop functionality for count down timer and also make changes in views.
hmsTimeFormatter(long milliSeconds) convert the milliseconds to HH:mm:ss time format.

Count Down Timer

Count Down Timer

DownloadCode
 
github

Enjoy Coding and Share Knowledge

  • SAmi Shiekh

    thanks

    • Admin

      Welcome Sami Shiekh ?

  • varinder

    sir this is amazing but sir please make second activity where user can save timer value in seconds and minuts please sir please

  • varinder

    sir can you make progress bar smooth

  • Jay Patel

    nice tutorial thanks this help me lot

    • Lalit Vasan

      Welcome jay

  • Optimum, saved my day. Thanks a lot.

    • Lalit Vasan

      Welcome slyther

  • Ainomaria Korhonen

    I would like to use this timer for input/display of seconds only. What changes should I make (apart from defining the time as *1000 instead of *6000)?

    • Lalit Vasan

      Hi Ainomaria,

      You are on the right track. Recently app is accepting input in minutes and converting that minutes to milliseconds. Make the change you mentioned and enter the seconds instead of minutes. And if you require modification in ui do that according.

      Hope this may help you

      Feel free to ask

  • Firas Kahia

    How to add sound before end 10 seconds countdown ???

    • Lalit Vasan

      Hi Firas,

      Android provides MediaPlayer class to play any media file.

      1) Add sound file like .mp3, .wav in raw folder located at app ⇒ src ⇒ main ⇒ res ⇒ raw. If raw folder not present create new one.

      2) Create MediaPlayer class object and pass context object and file id in create method of mediaplayer.
      MediaPlayer mp = MediaPlayer.create(this, R.raw.soundFileName);

      3) Use MediaPlayer start function to play sound.
      mp.start();

      * In your case put a condition in onTick() to play sound after 10 seconds.

      Hope this may help you

      Feel free to ask

      • Firas Kahia

        what use for condition if (… <=10) ??

        • Lalit Vasan

          Yes firas but keep in mind that the value in parameters of onTick function is in milliseconds.

  • Nauman Idrees

    progress bar not completed its rotation, last slice is not done…….What’s the reason?

    • Lalit Vasan

      What time did you entered? as I checked the app and video its working fine.

      • Nauman Idrees

        I have set value of 10 sec in countdown timer…….Actually, app is working fine, masla ye ha k last slice jo ha time ka wo complete nae hota, means 9 sec tak yellow progress bar chalta, us k bad khud sy reset state ma aa jata.

        • Lalit Vasan

          Actually that is the logic implemented in the app sample. when counter reaches the last second it will reset the progress bar.
          you can change that according to your need.

          • Nauman Idrees

            Can you please show me, in which function this is happening??

          • Lalit Vasan

            Look at the onFinish Function.

            countDownTimer = new CountDownTimer(timeCountInMilliSeconds, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            textViewTime.setText(hmsTimeFormatter(millisUntilFinished));

            progressBarCircle.setProgress((int) (millisUntilFinished / 1000));

            }

            @Override
            public void onFinish() {

            textViewTime.setText(hmsTimeFormatter(timeCountInMilliSeconds));
            // call to initialize the progress bar values
            setProgressBarValues();
            // hiding the reset icon
            imageViewReset.setVisibility(View.GONE);
            // changing stop icon to start icon
            imageViewStartStop.setImageResource(R.drawable.icon_start);
            // making edit text editable
            editTextMinute.setEnabled(true);
            // changing the timer status to stopped
            timerStatus = TimerStatus.STOPPED;
            }

            }.start();

          • Nauman Idrees

            When i have commented this below line in onFinish()
            setProgressBarValues();
            ProgressBar look like this after 9 seconds

            https://uploads.disquscdn.com/images/02b85a000f391301b09e61454b44f820a1e858d319ec4b2c40791fe7ed3f4383.png

            10th sec is not completed.

          • Lalit Vasan

            Also set the progressBarCircle.setProgress(0); in onFinish(). That will solve your problem.

          • Nauman Idrees

            Thanks…….It’s working

          • Lalit Vasan

            Welcome Nauman

Show Buttons
Hide Buttons