How to stop CountDownTimer in android

2019-03-25 10:53发布

How to stop this timer , any idea ?

I want to reset timer in every query but it continues. Every new query it adds new timer. How to solve this?

 new CountDownTimer(zaman, 1000) {                     //geriye sayma

            public void onTick(long millisUntilFinished) {

                NumberFormat f = new DecimalFormat("00");
                long hour = (millisUntilFinished / 3600000) % 24;
                long min = (millisUntilFinished / 60000) % 60;
                long sec = (millisUntilFinished / 1000) % 60;

                cMeter.setText(f.format(hour) + ":" + f.format(min) + ":" + f.format(sec));
            }

            public void onFinish() {
                cMeter.setText("00:00:00");
            }
        }.start();

3条回答
smile是对你的礼貌
2楼-- · 2019-03-25 11:20

you should define it as a variable

 CountDownTimer yourCountDownTimer = new CountDownTimer(zaman, 1000) {                     //geriye sayma

        public void onTick(long millisUntilFinished) {

            NumberFormat f = new DecimalFormat("00");
            long hour = (millisUntilFinished / 3600000) % 24;
            long min = (millisUntilFinished / 60000) % 60;
            long sec = (millisUntilFinished / 1000) % 60;

            cMeter.setText(f.format(hour) + ":" + f.format(min) + ":" + f.format(sec));
        }

        public void onFinish() {
            cMeter.setText("00:00:00");
        }
    }.start();

yourCountDownTimer.cancel();

Read more: https://developer.android.com/reference/android/os/CountDownTimer.html

查看更多
淡お忘
3楼-- · 2019-03-25 11:31

static CountDownTimer countDownTimer = null;

    if (countDownTimer != null) {
        countDownTimer.cancel();
    }
    countDownTimer = new CountDownTimer(50000, 1000) {
        public void onTick(long millisUntilFinished) {
            Log.e("seconds remaining : ", "seconds remaining : " + millisUntilFinished / 1000);
        }

        public void onFinish() {
            Log.e("done!", "done!");
        }
    };
    countDownTimer.start();
查看更多
看我几分像从前
4楼-- · 2019-03-25 11:38

You can call this.cancel() or simply cancel() inside one of its callback methods

查看更多
登录 后发表回答