Count Down Timer Code for Android Studio

Welcome. Here in this post you will learn how to add a Count Down Timer in Android Studio.

Count Down Timer Example for Android Studio

A count down timer works exactly as a timer that runs for the time given by you and stops automatically after the given time. Basically it is used to create any count down event and perform any task after the time is over.

Adding a Count Down timer in your App

Adding a countdown timer is very simple, just add these two lines of code in your app:-

Here the first time (10000 in our example) shows after how much time (in milliseconds) the timer will expire. And the second time shows the tick after how much time each tick will be counted (also in milliseconds).

A countdown Timer has some common functions, and they are:-

1. onTick (long millisUntilFinished )

This will perform an operation once after every tick occurs. The milisUntilFinished variable gives us the time remaining (in milliseconds) until the timer is over.

2. onFinish()

This method is used to perform any operation after the time is over and the timer has done its job.

3. cancel()

As the name suggests, this function is used to simply cancel the count down timer.

An image is shown below which demonstrates a countdown timer in action:-

The Full Java Code along with the XML layout for the above example is shown below:-

  • First Create a new project in Android Studio
  • File ⇒ New Android ⇒ Application Project
  • Then Open src -> package -> MainActivity.java and then add following code :

JAVA (MainActivity.java)

  •  Now Open res -> layout -> activity_main.xml and then add following code :

XML (activity_main.xml)

Output:

Finally, run this project.

This is how Android Count Down Timer Code look like.

Count Down Timer Code Count Down Timer Code Count Down Timer Code

You can directly copy paste these snippets to your android studio, and they should work perfectly. Just save and run your project. You can also try to play with other countdown timer settings on your own and see the corresponding changes accordingly. There are a variety of properties available which can be changed to make your timer work the way you want it to be.

For a more detailed guide, you can also visit android’s official guide below:-

https://developer.android.com/reference/android/os/CountDownTimer

With this we came to an end of our tutorial. Comment down below if you are facing any problems.

 

Also Read:-

Add a Comment

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