Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CountDownTimer.cancel() is not working in Android

CountDownTimer.cancel() is not working in the below code:

myTimer = new CountDownTimer(10000, 1000) {
    public void onFinish() {
    }
    @Override
    public void onTick(long millisUntilFinished) {
        if(null != myObject){
            myTimer.cancel();
        }
    }
}.start();

In the above code I have started a CountDownTimer which check if the object is not null and cancels the Timer accordingly. The object is set by some listener at any point of time. Please refer and suggest. Am I doing the right thing here?

Solution By Gautier Hayoun :

Just made a drop-in replacement for CountDownTimer that you can cancel from within onTick : Github link– Gautier Hayoun Dec 12 '10 at 1:04

like image 643
Vinayak Bevinakatti Avatar asked Jun 21 '11 10:06

Vinayak Bevinakatti


People also ask

How to use CountDown in android?

we can set count down time after completion of time it will stop and get 0 values. onTick(long millisUntilFinished ) - In this method we have to pass countdown mill seconds after done countdown it will stop Ticking. onFinish() - After finish ticking, if you want to call any methods or callbacks we can do in onFinish().

What is CountDown interval?

long : The number of millis in the future from the call to start() until the countdown is done and onFinish() is called. countDownInterval. long : The interval along the way to receive onTick(long) callbacks.


2 Answers

Solution By Gautier Hayoun :

Just made a drop-in replacement for CountDownTimer that you can cancel from within onTick : Github link– Gautier Hayoun Dec 12 '10 at 1:04

like image 136
Vinayak Bevinakatti Avatar answered Oct 27 '22 09:10

Vinayak Bevinakatti


Instead of CountDownTimer use TimerTask

final static long INTERVAL=1000;
final static long TIMEOUT=10000;


TimerTask task=new TimerTask(){
            @Override
            public void run() {
                elapsed+=INTERVAL;
                if(elapsed>=TIMEOUT){
                    this.cancel();
                    displayText("finished");
                    return;
                }
                //if(some other conditions)
                //   this.cancel();
                displayText("seconds elapsed: " + elapsed / 1000);
            }
        };
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, INTERVAL, INTERVAL);

private void displayText(final String text){
    this.runOnUiThread(new Runnable(){
        @Override
        public void run() {
            mTextField.setText(text);
        }
    });
}
like image 28
Sunil Kumar Sahoo Avatar answered Oct 27 '22 09:10

Sunil Kumar Sahoo