Android Count Down Timer Example

android.os.CountDownTimer is an abstract class that provides a count-down timer function. You must create a sub-class of it to use. This example will show you how to use android.os.CountDownTimer to implement a verification code retrieval function.

1. CountDownTimer Overview.

  1. android.os.CountDownTimer has bellow important methods that you should know.
  2. CountDownTimer(long millisInFuture, long countDownInterval): This is the constructor method, you should override this method in it’s sub-class.
    millisInFuture: Millisecond’s number that this counter will count.
    countDownInterval: Millisecond’s number between each count event. When this time interval happened, the counter’s onTick(long millisUntilFinished) method will be invoked.
  3. synchronized final CountDownTimer start(): Start CountDownTimer object.
  4. synchronized final void cancel(): Cancel CountDownTimer object.
  5. abstract void onTick(long millisUntilFinished): This is a callback method that will be invoked every count down interval time passed.
    millisUntilFinished
    : The left time in milliseconds.
  6. abstract void onFinish(): This method will be invoked when the count down timer finish.

2. CountDownTimer Example Overview.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/1zvRLLw52DY

  1. This example will use android.os.CountDownTimer to implement send a verification code button.
  2. When the user clicks the button, the button is disabled, and left time will be shown in the button. After 60 seconds, the button is enabled again.

3. CountDownTimer Example Files.

  1. Below is the example java files, they are MyCountDownTimer.java and CountDownTimerActivity.java.
    android-count-down-timer-java-file
  2. Below is the example layout XML file, the file name is activity_count_down_timer.xml.
    android-count-down-timer-layout-xml-file
  3. MyCountDownTimer.java
    package com.dev2qa.example.view;
    
    import android.os.CountDownTimer;
    import com.dev2qa.example.CountDownTimerActivity;
    
    /**
     * This is CountDownTimer sub class, which will override it's abstract methods.
     */
    
    public class MyCountDownTimer extends CountDownTimer {
    
        // This variable refer to the source activity which use this CountDownTimer object.
        private CountDownTimerActivity sourceActivity;
    
        public void setSourceActivity(CountDownTimerActivity sourceActivity) {
            this.sourceActivity = sourceActivity;
        }
    
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }
    
        @Override
        public void onTick(long millisUntilFinished) {
            if(this.sourceActivity!=null) {
                // Invoke source activity's tick event method.
                this.sourceActivity.onCountDownTimerTickEvent(millisUntilFinished);
            }
        }
    
        @Override
        public void onFinish() {
            if(this.sourceActivity!=null)
            {
                // Invoke source activity's tick event method.
                this.sourceActivity.onCountDownTimerFinishEvent();
            }
        }
    }
  4. CountDownTimerActivity.java
    package com.dev2qa.example;
    
    import android.os.Bundle;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    
    import com.dev2qa.example.view.MyCountDownTimer;
    
    public class CountDownTimerActivity extends AppCompatActivity {
    
        private Button buttonSendVerifyCode;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_count_down_timer);
    
            setTitle("CountDownTimer Example");
    
            // Create a count down timer which will count 60 seconds and invoke the timer object onTick() method every second.
            final MyCountDownTimer myCountDownTimer = new MyCountDownTimer(60*1000, 1000);
            // Set count down timer source activity.
            myCountDownTimer.setSourceActivity(this);
    
            // Get the send verify code button.
            buttonSendVerifyCode = (Button)findViewById(R.id.buttonSendVerifyCode);
            buttonSendVerifyCode.setAllCaps(false);
            buttonSendVerifyCode.setTextSize(25);
            buttonSendVerifyCode.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Start the count down timer.
                    myCountDownTimer.start();
                    // Disable send verify code button.
                    buttonSendVerifyCode.setEnabled(false);
    
                    AlertDialog alertDialog = new AlertDialog.Builder(CountDownTimerActivity.this).create();
                    alertDialog.setMessage("Verification code has been send through sms. " +
                            "Click this button to resend 60 seconds later.");
                    alertDialog.show();
                }
            });
        }
    
        /* This method will be invoked when CountDownTimer finish. */
        public void onCountDownTimerFinishEvent()
        {
            this.buttonSendVerifyCode.setEnabled(true);
        }
    
        /* This method will be invoked when CountDownTimer tick event happened.*/
        public void onCountDownTimerTickEvent(long millisUntilFinished)
        {
            // Calculate left seconds.
            long leftSeconds = millisUntilFinished / 1000;
    
            String sendButtonText = "Left " + leftSeconds + " (s)";
    
            if(leftSeconds==0)
            {
                sendButtonText = "Send Verification Code";
            }
    
            // Show left seconds in send button.
            this.buttonSendVerifyCode.setText(sendButtonText);
        }
    }
  5. activity_count_down_timer.xml
      <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            tools:layout_editor_absoluteY="8dp"
            tools:layout_editor_absoluteX="8dp">
    
            <TextView
                android:id="@+id/textView11"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Click below Send button to get verification code via sms. Then enter the code in the text box."
                android:textSize="25sp"/>
    
            <EditText
                android:id="@+id/editText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="textPersonName"
                android:hint="Enter Verification Code" />
    
            <Button
                android:id="@+id/buttonSendVerifyCode"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Send Verification Code" />
      </LinearLayout>

1 thought on “Android Count Down Timer Example”

  1. Torbjörn Dahlquist

    Hi !
    I would like to create a timer with the following properties.
    1: selectable time to start.
    2: selectable time ON.
    3: selectable time OFF
    4: selection of the number of repetitions
    5: and emergency stop

    How do I do then?

    Regards Seaman

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.