You are currently viewing How to use Android CountDownTimer?

How to use Android CountDownTimer?

The CountDownTimer is a class in Android, which is used to set a countdown based on the time interval.  In countdown timer, you can set the Timer, and after completion of the timer, it will stop. In this article, we will see how we can use Android CountDownTimer class to create a countdown application.

Methods of Countdown Timer

The countdown timer has four methods as mentioned below, we will use these methods in or example.

  • onTick (): on tick, we have to give the time interval
  • onFinish(): after finish the timer it will stop and if you want to perform any time task after finish you can perform any task
  • start(): To start the timer
  • cancel (): Cancel the countdown.

CountDownTimer Basic Code

Below is the sample basic code for CountDowntimer.

public CountDownTimer (long millisInFuture, 
                long countDownInterval)

The parameters of the CountDownTimer are defined as follows :

  • millisInFuture: The number of milliseconds in the future from the call to start() until the countdown is done and onFinish() is called.
  • countDownInterval: The interval along the way to receive onTick(long) callbacks

Sample Code

No, let us create a count down app step by step. In this example, we will create a sample count down which starts from 10 and ends on 0.

Create the XML Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/layout"
    android:gravity="center"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:id="@+id/timer"
        android:layout_width="match_parent"
        android:gravity="center"
        android:layout_height="wrap_content" />
</LinearLayout>

Create the Activity File

package com.example.myapplication;

import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
TextView timer;
int runcounter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        timer=findViewById(R.id.timer);

        new CountDownTimer(30000, 1000) {

            public void onTick(long millisUntilFinished) {
                timer.setText(String.valueOf(runcounter));
                runcounter++;
            }

            public void onFinish() {

                timer.setText("Timer Stop");

            }

        }.start();

    }
}

After the timer is stopped, you can perform other actions, like redirecting to another page or displaying some message on the same page.

Leave a Reply