Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop/cancel android CountDownTimer

Tags:

android

I'm extending the CountDownTimer class to obtain some custom functionality .In onTick() in case some conditions are met I call cancel() , expecting that will be the end of it, however the onTick() callback gets call until the the count down is reached . So how to prevent this from happening ?

like image 770
rantravee Avatar asked Jun 29 '10 06:06

rantravee


People also ask

How do I know if a countdown timer is running?

After start -> make it true; Inside OnTick -> make it true (not actually required, but a double check) Inside OnFinish -> make it false; use the isTimerRunning property to track the status. Show activity on this post. Check if the CountDownTimer is Running and also if the app is running in the background.


2 Answers

CountDownTimer.cancel() method seems to be not working. Here's another thread without a solution Timer does not stop in android.

I would recommend you to use Timer instead. It's much more flexible and can be cancelled at any time. It may be something like that:

public class MainActivity extends Activity {    
    TextView mTextField;
    long elapsed;
    final static long INTERVAL=1000;
    final static long TIMEOUT=5000;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mTextField=(TextView)findViewById(R.id.textview1);

        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 114
Fedor Avatar answered Nov 11 '22 08:11

Fedor


CountDownTimer is also working fine for me, but I think it only works if you call it OUTSIDE of the CountDownTimer implemetation (that is don't call it in the onTick).

Calling it inside also didn't worked.

like image 35
maid450 Avatar answered Nov 11 '22 10:11

maid450