Home » Android » Android countdown

Android countdown

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to write a countdown in android which starts counting from 3 to 0. Like at first 3 in appearing and then disappearing and 2 is appearing and so on. I searched a lot but I couldn’t find any good sample. Can you help me that what should I do?

How to&Answers:

use CountDownTimer

For example:

import android.os.CountDownTimer;   

MyCount timerCount;
public class TestCountdown extends Activity {

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    timerCount = new MyCount(3 * 1000, 1000);
    timerCount.start();
  }

  public class MyCount extends CountDownTimer {
      public MyCount(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
      }

      @Override
      public void onFinish() {
        //some script here
      }

      @Override
      public void onTick(long millisUntilFinished) {
        //some script here 
      }   
    } 
}

Answer:

The good guys in Android thought about you.

You have a class for that – CountDownTimer.

Answer:

I am not going to write you the code for this but this should not be difficult.Just use a thread to display the value 3(using say TextView) first then sleep for say (100ms assuming you want it to change after 1 sec) then decrease it and repeat.

An example would be

for i=0 to 3
print the number 
thread.sleep(100)