java - 你如何取消 CountDownTimer?

标签 java android timer

我有一个带有倒数计时器的 AlertDialog,我有一个取消按钮设置,它取消了对话框,但计时器继续运行!有谁知道如何取消倒数计时器的倒计时?任何帮助将不胜感激!

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

}

最佳答案

您似乎在对话框上调用取消,但从未在计时器上调用。您需要维护对 CountDownTimer 的引用,并在您的 onClick 方法中调用它的 cancel 方法。

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

关于java - 你如何取消 CountDownTimer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10904933/

相关文章:

java - 如何在 Java 中获取父 URL?

delphi - 如何防止计时器和套接字事件同时更改列表?

c - 可以检索 glib 'event?' 上剩余的时间

c# - 在 C# 中完成处理后如何停止 ffmpeg 进程?

Java 粘液 Volley 图像闪烁

java - 可运行jar文件创建-jar包中包含的资源文件夹

Java 没有给出错误!

android - 如何禁用使用 Flutter 1.0 在 Google map 中点击标记时出现的导航按钮?

android - 有没有内置的方法来检测 okhttp 中未连接的互联网?

android - 如何在 TextView 中显示背景图像