Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 722
William L. Avatar asked Dec 01 '22 23:12

William L.


1 Answers

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();
}
like image 159
wolfcastle Avatar answered Dec 05 '22 09:12

wolfcastle