How to cancel CountDownTimer?

I have an AlertDialog with a countdown timer in it, and I have a cancel button, and it cancels the dialog, but the timer continues to move! Does anyone know how to cancel the countdown of the 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(); } 
+4
source share
2 answers

It looks like you are calling cancel in a dialog box, but never on a timer. You need to save the reference to CountDownTimer and call the cancel method in the 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(); } 
+15
source

Call cancel() method on CountDownTimer

+2
source

Source: https://habr.com/ru/post/1416251/


All Articles