2

I have got an application where I need to show counter from 3 to 1 then quickly switch to another activity. Will TimerTask will be suitable for doing this? Can anybody show me an example of exactly how to do it?

CountDownTimer Worked. Code for showing timer for 3 seconds is.

new CountDownTimer(4000, 1000) {

             public void onTick(long millisUntilFinished) {
                 Animation myFadeOutAnimation = AnimationUtils.loadAnimation(countdown.this, R.anim.fadeout);       
                 counter.startAnimation(myFadeOutAnimation);
                 counter.setText(Long.toString(millisUntilFinished / 1000));
             }

             public void onFinish() {
                 counter.setText("done!");
             }
        }.start();
Ayaz Alavi
  • 4,825
  • 8
  • 50
  • 68

2 Answers2

14

I would better use a CountDownTimer.

If you want for example your counter to count 3 seconds:

//new Counter that counts 3000 ms with a tick each 1000 ms
CountDownTimer myCountDown = new CountDownTimer(3000, 1000) {
    public void onTick(long millisUntilFinished) {
        //update the UI with the new count
    }

    public void onFinish() {
        //start the activity
   }
};
//start the countDown
myCountDown.start();
maid450
  • 7,478
  • 3
  • 37
  • 32
  • there is a small type this: CountDownTimer myCountDown = new CountdownTimer(3000, 1000) { should be this: CountDownTimer myCountDown = new CountDownTimer(3000, 1000) { Capital D in the new CountDownTimer :) – AlAsiri Jan 16 '14 at 19:40
  • Simple but sure! Thanks – Arief Rivai Mar 31 '14 at 06:00
2

Use CountDownTimer as shown below.

Step1: create CountDownTimer class

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

        public void onFinish() {
            dialog.dismiss();
           // Use Intent to Navigate from this activity to another
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
        }
}

Step2: create an object for that class

MyCount counter = new MyCount(2000, 1000); // set your seconds
counter.start();
sanyassh
  • 8,100
  • 13
  • 36
  • 70
Sankar Ganesh PMP
  • 11,927
  • 11
  • 57
  • 90