Timer in Android

In this tutorial we will learn how to use Timer() class in Android. Timer can be used like countdown timer clock.

Timer in android
Timer in android

What is Timer() Class in Android?

Timer is a class in android which is used to perform some task according to time period. Like countdown clock. Or we can call any function after some time like after 2 minutes using timer class.

A facility for threads to schedule task for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.

Below are some of the examples of Timer class.

We can set the background thread, can schedule a task, can execute the task in one time or after time interval using Timer .

Creating Count Down Timer.

As we know that in the mobiles and watches the count down timer starts from the given time and stop when the time complete to 0. Below is the example of count down timer.

There are 4 methods of countdown timer:

onTick(long millisUntilFinished) – We have to pass the time for count down.

onFinish()- After finishing the time , we can all any method here.

start()- Used to call the count down timer.

cancel() – We can cancel the timer by calling the cancel method.

Below is the complete example of Count Down Timer in Android.

package com.example.androidtestingproject.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.androidtestingproject.R;
public class TestActivity extends AppCompatActivity {
    TextView textTimer;
    public int counter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        textTimer = findViewById(R.id.textTimer);

        new CountDownTimer(50000, 1000){
            @Override
            public void onTick(long millisUntilFinished) {
                textTimer.setText(String.valueOf(counter));
                counter++;
            }

            @Override
            public void onFinish() {
                textTimer.setText("Count Down Timer finished");
            }
        }.start();

    }

}

Thank you for visiting the tutorial on FlutterTPoint. Please visit more useful Android Tutorials which will help you to improve your development skills fast.

close

Don’t miss new tips!

We don’t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment