再次启动CountDownTimer - android

时间:2013-11-12 12:19:12

标签: android timer

我读到没有直接的方法重新开始(或更新)时间。我试着这样做:

Const.counter = new CustomTimerTask(Const.currentLevel.timeGoal * 1000,1000, importantMessage, showTimerMessage);
                Const.counter.start();

每次我希望计时器重新启动但它不起作用(旧计时器保持不变)。我该怎么办?

编辑: 我也试试这个

if(Const.counter != null){
                    Const.counter.cancel();
                    Const.counter.start();
                }
                else{
                    Const.counter = new CustomTimerTask(Const.currentLevel.timeGoal * 1000,1000, importantMessage, showTimerMessage);
                    Const.counter.start();
                }

但它暂停并恢复,不再重新开始

编辑2:也许我会写更多代码:

package com.example.fishe;

import android.os.CountDownTimer;
//countdowntimer is an abstract class, so extend it and fill in methods

public class CustomTimerTask extends CountDownTimer{

    private Messages gameoverMes;
    private Messages showRemailTimeMes;

    public CustomTimerTask(long millisInFuture, long countDownInterval , Messages gameoverMes , Messages showRemailTimeMes) {
        super(millisInFuture, countDownInterval);
        this.gameoverMes = gameoverMes;
        this.showRemailTimeMes =showRemailTimeMes;
    }

    @Override
    public void onFinish() {
        gameoverMes.setMessage("GAME OVER");
        showRemailTimeMes.setMessage(" " + 0);
        Game.gameOver();
    }

    @Override
    public void onTick(long millisUntilFinished) {
        Const.secUntilFinished = millisUntilFinished/1000;
        if( Const.secUntilFinished == 6)
            GameSounds.play(Const.TIME_GOING_TO_OVER,false);
        showRemailTimeMes.setMessage(" " + Const.secUntilFinished);
    }
}

我总是看到" 0"在showDemailTimeMes之后第一个计数器我确定完成后, 虽然我再次开始计算。

@Override
    public void onResume()
    {

        super.onResume();



        if(Const.counter != null){
            Const.counter = null;
        }
        Const.counter = new CustomTimerTask(Const.currentLevel.timeGoal * 1000,1000,
                importantMessage, showTimerMessage);
        Const.counter.start();
}

1 个答案:

答案 0 :(得分:1)

你可以做的只是销毁CountDownTimer的前一个实例并重新初始化新实例,如,

if(Const.counter != null){
     Const.counter = null;
  }
 Const.counter = new CustomTimerTask(Const.currentLevel.timeGoal * 1000,1000,
                                             importantMessage, showTimerMessage);
 Const.counter.start();