Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaCountDownTimer in Android with Example

CountDownTimer in Android with Example

The countdown timer app is about setting a time that moves in reverse order as it shows the time left in the upcoming event. A countdown timer is an accurate timer that can be used for a website or blog to display the countdown to any special event, such as a birthday or anniversary. Likewise, here let’s create an Android App to learn how to create a simple countdown App. So let’s begin app creation step by step towards its completion.

countdowntimer

Step-by-Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.

Step 2: Working with the XML files

In the activity_main.xml file add only a TextView to display the CountDownTimer. Below is the complete code for the activity_main.xml file.

Step 3: Working with the MainActivity file

Now In the MainActivity file, create an object of TextView and map the components(TextView) with their id. 

// Initializing thetextView
TextView textView;
textView = findViewById (R.id.textView);

Schedule a countdown until a time in the future, with regular notifications at intervals along the way. Example of showing a 50-second countdown in a text field:

new CountDownTimer(50000, 1000) {
    public void onTick(long millisUntilFinished) {
        // Used for formatting digit to be in 2 digits only
        NumberFormat f = new DecimalFormat("00");
        long hour = (millisUntilFinished / 3600000) % 24;
        long min = (millisUntilFinished / 60000) % 60;
        long sec = (millisUntilFinished / 1000) % 60;
        textView.setText(f.format(hour) + ":" + f.format(min) + ":" + f.format(sec));
    }
    // When the task is over it will print 00:00:00 there
    public void onFinish() {
        textView.setText("00:00:00");
    }
}.start();

The complete code for the MainActivity file is given below.

Output: Run on Emulator

PulseCountDown

PulseCountDown in Android is an alternative to CountDownTimer. It is very easy to implement PulseCountDown instead of CountDownTimer because PulseCountDown provides a default layout with some beautiful animations. By default start value of PulseCountDown is 10 and the end value is 0. Suppose there needs a quiz app, and that adds a time limit to answer a question there PulseCountDown can be used. To implement PulseCountDown please refer PulseCountDown in Android with an Example.
 

pulse countdown

Pulse Count Down

RELATED ARTICLES

Most Popular

Recent Comments