首页 > 解决方案 > 我在 android studio 中制作计时器时遇到问题

问题描述

在应用程序中,我重新打开了与计时器相同的活动。第一次计时器工作,但之后它开始onFinish()在随机时间窃听运行。我该如何解决?

new CountDownTimer(10000, 1000) {
    public void onTick(long millisUntilFinished) {
        textQuestion.setText("seconds remaining: " + millisUntilFinished / 1000);
    }
    public void onFinish() {
        wrongAnswer();
    }
}.start();

标签: javaandroidtimercountdowntimer

解决方案


您必须将 CountDownTimer 存储在计时器中,并在您移动到另一个活动或片段时取消它;

创建CountDownTimer为全局变量(在 onCreate 之上)

CountDownTimer timer;

在您想要启动计时器的地方或任何时候初始化计时器

timer = new CountDownTimer(10000, 1000) {

        public void onTick(long millisUntilFinished) {
            textQuestion.setText("seconds remaining: " + millisUntilFinished / 1000);
        }

        public void onFinish() {
            wrongAnswer();
        }
    }.start();

onDestroy取消它

@Override
protected void onDestroy() {
    if(timer != null) timer.cancel();
    super.onDestroy();
}

推荐阅读