How to stop CountDownTimer in android

删除回忆录丶 提交于 2019-12-18 13:03:09

问题


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

回答1:


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




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/40203827/how-to-stop-countdowntimer-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!