Android Count Down Timer Example

android.os.CountDownTimer is an abstract class which provide 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 verification code retrieval function.

1. CountDownTimer Overview.

android.os.CountDownTimer has bellow important methods that you should know.

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

2. CountDownTimer Example Overview.

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

android count down timer example

3. CountDownTimer Example Files.

android count down timer java file

android count down timer layout xml file

MyCountDownTimer.java

package com.dev2qa.example.view;

import android.os.CountDownTimer;
import com.dev2qa.example.CountDownTimerActivity;

/**
 * Created by Jerry on 10/31/2017.
 * 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();
        }
    }
}

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);
    }
}

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>

Download “Android-Count-Down-Timer-Example.zip” Android-Count-Down-Timer-Example.zip – Downloaded 126 times – 2 KB

(Visited 2,449 times, 14 visits today)
READ :   Android ListView Example

Leave a Reply

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.