Taha
Taha

Reputation: 357

How to stop CountDownTimer in android

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

Upvotes: 30

Views: 64266

Answers (4)

Amir_P
Amir_P

Reputation: 9019

You can assign it to a variable and then call cancel() on the variable

CountDownTimer yourCountDownTimer = new CountDownTimer(zaman, 1000) {                    
    public void onTick(long millisUntilFinished) {}

    public void onFinish() {}

    }.start();

yourCountDownTimer.cancel();

or you can call cancel() inside of your counter scope

new CountDownTimer(zaman, 1000) {                    
    public void onTick(long millisUntilFinished) {
        cancel();
    }

    public void onFinish() {}

    }.start();

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

Upvotes: 93

kamal khalaf
kamal khalaf

Reputation: 111

In kotlin you can use this command

countDownTimer?.cancel()

Upvotes: 0

Dhiraj Kumar
Dhiraj Kumar

Reputation: 173

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

Upvotes: 2

Luca Murra
Luca Murra

Reputation: 1888

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

Upvotes: 10

Related Questions