William L.
William L.

Reputation: 3886

How do you cancel CountDownTimer?

I have a AlertDialog with a countdown timer in it, and I have a cancel button setup and it cancels the dialog but the timer keeps going! Does anyone know how to cancel the countdown of a countdown timer? Any help would be appreciated!

   private void timerDialog() {
    timerDialog = new AlertDialog.Builder(this).create();  
    timerDialog.setTitle("Timer");  
    timerDialog.setMessage("Seconds Remaining: "+timerNum*1000);
    timerDialog.setCancelable(false);
    timerDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface aboutDialog, int id) {
           timerDialog.cancel();
        }
    });
    timerDialog.show();
    new CountDownTimer(timerNum*1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            timerDialog.setMessage("Seconds Remaining: "+ (millisUntilFinished/1000));
        }

        @Override
        public void onFinish() {
            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(500);
            timerDialog.cancel();
        }
    }.start();

}

Upvotes: 4

Views: 15053

Answers (2)

wolfcastle
wolfcastle

Reputation: 5930

You appear to be calling cancel on the Dialog, but never on the timer. You need to maintain a reference to the CountDownTimer, and call its cancel method in your onClick method.

private void timerDialog() {
    final CountDownTimer timer = new CountDownTimer(timerNum*1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            timerDialog.setMessage("Seconds Remaining: "+ (millisUntilFinished/1000));
        }

        @Override
        public void onFinish() {
            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(500);
            timerDialog.cancel();
        }
    };
    timerDialog = new AlertDialog.Builder(this).create();  
    timerDialog.setTitle("Timer");  
    timerDialog.setMessage("Seconds Remaining: "+timerNum*1000);
    timerDialog.setCancelable(false);
    timerDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface aboutDialog, int id) {
           timer.cancel();
        }
    });
    timerDialog.show();
    timer.start();
}

Upvotes: 17

Eduardo Sanchez-Ros
Eduardo Sanchez-Ros

Reputation: 1827

Call the cancel() method on CountDownTimer

Upvotes: 3

Related Questions