9

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

Vinayak Bevinakatti
  • 40,205
  • 25
  • 108
  • 139
  • 1
    The problem might be that you are referencing `myTimer` inside the newly created object. Try `this.cancel();` instead of `myTimer.cancel();`. – Pit Jun 21 '11 at 11:11
  • 2
    is this a Android bug? I am really frustrated because of this. – Shirish Herwade Jun 28 '16 at 11:04

2 Answers2

9

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

Vinayak Bevinakatti
  • 40,205
  • 25
  • 108
  • 139
  • The handler in this gives warning 'This Handler class should be static or leaks might occur'.. Read: http://stackoverflow.com/questions/11407943/this-handler-class-should-be-static-or-leaks-might-occur-incominghandler – Rajat Singhal Nov 13 '15 at 17:50
5

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);
        }
    });
}
grebulon
  • 7,697
  • 5
  • 42
  • 66
Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243