Реализация счетчика в Android

У меня есть приложение, где мне нужно показать счетчик от 3 до 1, а затем быстро переключиться на другое действие. Будет ли TimerTask подходящим для этого? Может ли кто-нибудь показать мне пример того, как это сделать?

Работает CountDownTimer. Код для показа таймера в течение 3 секунд.

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();

Ответ 1

Я бы лучше использовал CountDownTimer.

Если вы хотите, чтобы ваш счетчик подсчитал 3 секунды:

//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();

Ответ 2

  Use CountDown Timer as Shown below

Шаг1:

    Create  Count Down Timer 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

        }


       }

Шаг 2:   Создайте объект для этого класса

 MyCount counter = new MyCount(2000, 1000); // set your seconds
   counter.start();