CountDownTimer值永远不会变为零

时间:2016-06-02 13:32:35

标签: java android timer

我将定时器初始化为11000 ms并且使用日志我看到定时器从10959ms到1484ms

DocumentFile

这里有什么问题?

2 个答案:

答案 0 :(得分:1)

我最终创建了自己的计时器:

public abstract class CountDownTimer {

    private static final String TAG = CountDownTimer.class.getSimpleName();

    private static final long TIMER_DEFAULT = 4000; //ms
    private static final long TIMER_STEP    = 1000; //ms

    private boolean mIsRunning = false;

    private long mRemainingTime = 0;
    private long mTotalTime;

    private Handler mHandler = new Handler();

/**
 * Callback fired on regular interval.
 *
 * @param millisUntilFinished The amount of time until finished.
 */
public abstract void onTick(long millisUntilFinished);

/**
 * Callback fired when the time is up.
 */
public abstract void onFinish();

public CountDownTimer(long timerStartValue) {

    if (timerStartValue >= 1) {
        mTotalTime = timerStartValue * TIMER_STEP;
        mRemainingTime = timerStartValue * TIMER_STEP;
    } else {
        mTotalTime = TIMER_DEFAULT;
        mRemainingTime = TIMER_DEFAULT;
    }
}

public CountDownTimer start() {

    mIsRunning = true;

    // Start the initial runnable task by posting through the handler
    mHandler.postDelayed(runnableCode, TIMER_STEP);
    return this;
}

public void cancel() {
    mIsRunning = false;
    mHandler.removeCallbacks(runnableCode);
}

private Runnable runnableCode = new Runnable() {
    @Override
    public void run() {

        if (mRemainingTime >= 0) {
            onTick(mRemainingTime);
        } else {
            mIsRunning = false;
            onFinish();
        }

        mRemainingTime -= TIMER_STEP;

        if (mIsRunning) {
            // Goes on
            mHandler.postDelayed(runnableCode, TIMER_STEP);
            }
        }
    };

}

答案 1 :(得分:0)

您刚刚开始使用 CountDownTimer

的创建对象

要么必须像这样创建:

private void startGameCountDown() {
    new CountDownTimer(30000, 1000) {

        public void onTick(long millisUntilFinished) {
            Log.i(TAG, "onTick: " + millisUntilFinished);

            mTimerTv.setText(String.format("%d", millisUntilFinished));
            mTimerTv.invalidate();
        }

        public void onFinish() {
            mTextField.setText("done!");
        }

    }.start();
}

或者您可以创建对象,然后就可以像这样启动它

private void startGameCountDown() {

    CountDownTimer mCountDownTimer = new CountDownTimer(11000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {

            Log.i(TAG, "onTick: " + millisUntilFinished);

            mTimerTv.setText(String.format("%d", millisUntilFinished));
            mTimerTv.invalidate();
        }

        @Override
        public void onFinish() {
        }
    };
    mCountDownTimer.start();
}