Count Down Timer in Android

Count Down Timer in Android

Today we are going to create a CountDownTimer in Android. CountDownTimer is used to Schedule a countdown until a time in the future, with regular notifications on intervals along the way. For this we are going to use inbuilt CountDownTimer abstract class.

Basically CountDownTimer is working on Seconds but we can manipulate it to work on Minutes, Hours or Days. So in this tutorial also we are going to convert seconds into Hour, Minutes and Seconds.

VIDEO DEMO

1. Create a new project in Android Studio by navigating to File ⇒ New ⇒ New Project and fill required details. By default my activity is MainActivity.java.

2. Open strings.xml located under res=>values folder and add following strings. These strings are going to be used in this example.

3. Now create a layout naming activity_main.xml and add the following code. In this there are two button for start/stop and reset timer, an EditText for entering no of minutes to run timer and a TextView for running timer.

4. The below method startTimer(int noOfMinutes) is going to be used for countdown timer. There are  three methods in CountDownTimer class:

  • onTick(long millisUntilFinished) – When a count down start this method will run and we can display the Tick over TextView.
  • onFinish() – When CountDown finished then this method called.
  • onCancel() – This method is used for cancelling CountDownTimer.
5. Finally come to your MainActivity.java and add the following code. The code is very simple to use CountDownTimer. You can implement this code in your project.
6. Finally, run the application and you will get the output as shown in video.

Thanks. :)

Download Source Code – >

COMMENTS (2)
Reply

It will work well but when i close application it stops and reset from start. so can you help me how can i start timer from left time.

    HI Madhav,

    To start the timer from where you left it, You have to save the last time in SharedPreferences and then when you open your activity again that time read the value from SharedPreference. If value exist start timer from there else start from 0.

    Thanks

Leave a Comment

Comment (required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Name (required)
Email (required)