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.
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.
1 2 3 4 5 6 7 8 9 |
<resources> <string name="app_name">CountDownTimer Demo</string> <string name="enter_minutes">Minutes!</string> <string name="start_timer">Start Timer</string> <string name="stop_timer">Stop Timer</string> <string name="reset_timer">Reset Timer</string> <string name="timer">00:00:00</string> </resources> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#EEEEEE" android:gravity="center" android:orientation="vertical" android:padding="10dp"> <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/enterMinutes" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_toLeftOf="@+id/startTimer" android:hint="@string/enter_minutes" android:padding="10dp" android:maxLength="4" android:inputType="number" android:textSize="16sp" android:gravity="center" android:textColor="#000000" android:textColorHint="#9E9E9E" /> <Button android:id="@+id/startTimer" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="10dp" android:background="#009688" android:padding="10dp" android:textColor="#ffffff" android:textSize="16sp" android:text="@string/start_timer" /> </RelativeLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/countdownText" android:gravity="center" android:layout_gravity="center_horizontal" android:textSize="30sp" android:text="@string/timer" android:layout_marginTop="25dp" android:textStyle="bold" android:textColor="#4CAF50"/> <Button android:id="@+id/resetTimer" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:background="#009688" android:padding="10dp" android:textColor="#ffffff" android:textSize="16sp" android:text="@string/reset_timer" /> </LinearLayout> |
4. The below method startTimer(int noOfMinutes) is going to be used for countdown timer. There are three methods in CountDownTimer class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
private void startTimer(int noOfMinutes) { CountDownTimer countDownTimer = new CountDownTimer(noOfMinutes, 1000) { public void onTick(long millisUntilFinished) { long millis = millisUntilFinished; //Convert milliseconds into hour,minute and seconds String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); countdownTimerText.setText(hms);//set text } public void onFinish() { countdownTimerText.setText("TIME'S UP!!"); //On finish change timer text } }.start(); } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
package com.countdowntimer_demo; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.util.concurrent.TimeUnit; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static TextView countdownTimerText; private static EditText minutes; private static Button startTimer, resetTimer; private static CountDownTimer countDownTimer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); countdownTimerText = (TextView) findViewById(R.id.countdownText); minutes = (EditText) findViewById(R.id.enterMinutes); startTimer = (Button) findViewById(R.id.startTimer); resetTimer = (Button) findViewById(R.id.resetTimer); setListeners(); } //Set Listeners over button private void setListeners() { startTimer.setOnClickListener(this); resetTimer.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.startTimer: //If CountDownTimer is null then start timer if (countDownTimer == null) { String getMinutes = minutes.getText().toString();//Get minutes from edittexf //Check validation over edittext if (!getMinutes.equals("") && getMinutes.length() > 0) { int noOfMinutes = Integer.parseInt(getMinutes) * 60 * 1000;//Convert minutes into milliseconds startTimer(noOfMinutes);//start countdown startTimer.setText(getString(R.string.stop_timer));//Change Text } else Toast.makeText(MainActivity.this, "Please enter no. of Minutes.", Toast.LENGTH_SHORT).show();//Display toast if edittext is empty } else { //Else stop timer and change text stopCountdown(); startTimer.setText(getString(R.string.start_timer)); } break; case R.id.resetTimer: stopCountdown();//stop count down startTimer.setText(getString(R.string.start_timer));//Change text to Start Timer countdownTimerText.setText(getString(R.string.timer));//Change Timer text break; } } //Stop Countdown method private void stopCountdown() { if (countDownTimer != null) { countDownTimer.cancel(); countDownTimer = null; } } //Start Countodwn method private void startTimer(int noOfMinutes) { countDownTimer = new CountDownTimer(noOfMinutes, 1000) { public void onTick(long millisUntilFinished) { long millis = millisUntilFinished; //Convert milliseconds into hour,minute and seconds String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); countdownTimerText.setText(hms);//set text } public void onFinish() { countdownTimerText.setText("TIME'S UP!!"); //On finish change timer text countDownTimer = null;//set CountDownTimer to null startTimer.setText(getString(R.string.start_timer));//Change button text } }.start(); } } |
6. Finally, run the application and you will get the output as shown in video.
Thanks.
Subscribe to us and get the latest news.
12 Comments
madhav
Wednesday, October 12th, 2016It 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.
Dr. Droid
Wednesday, October 12th, 2016HI 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
Nur subhan
Sunday, December 25th, 2016Hello Dr.Droid
I wanted to create a multi countdown ,.Can you help me,.??
please
😀
Dr. Droid
Monday, December 26th, 2016Hi Nur Subhan,
To create MultiCountdown there are two ways:
1. Create multiple CountDownTimer instance and use them as to start and stop timer. (I am not sure that this will work out or not)
2. Create a ListView and add the number of rows and in every row put your timer and there you have to start it and stop. (This will work out.)
For 2nd Way you can have look to this StackOverFlow Solution:
http://stackoverflow.com/questions/6346075/android-multiple-simultaneous-count-down-timers-in-a-listview
Thanks
ismail
Monday, December 26th, 2016Thanks you.
i will use in my project
Nur subhan
Tuesday, January 3rd, 2017Sory Dr. Droid
I can not understand all of that code
please give me a tutorial from you
:'(
Dilyan
Thursday, May 11th, 2017Hello,
Can you explain me how to make a resume button in this code.
Thanks in advanced 🙂 !
Dr. Droid
Thursday, May 11th, 2017Hi Dilyan,
Unfortunately there is no resume functionality in Count Down but there is other way to do this. For this whenever you stop the timer you need to save the time in SharedPreference and when you click on Resume button that time get the remaining time by subtracting total time – save time = time_remaining. This remaining_time will be your current time for which you have to run the count down.
Hope you understand.
Thanks
pppp
Friday, June 2nd, 2017How to manipulate it for number of days, as i am trying but its not giving the correct value
Dr. Droid
Saturday, June 3rd, 2017Hi PPPP,
I don’t know what logic you are using. I am telling my logic please cross check with yours one and try it.
1. Convert the milliseconds into hours.
2. After convert hours into number of days by : hours/24.
In this way you will get the countdown timer into number of days.
Thanks
Muzammal Rasheed
Friday, January 11th, 2019thankew best Tutorial <3
Athul Thomas
Friday, February 22nd, 2019thank you very much sir….its working