ScheduledThreadPoolExecutor只有"滴答"一旦

时间:2015-04-08 18:11:30

标签: android runnable

我在我的CountDownTimer中使用了Activity来进行倒计时功能。我决定退出CountDownTimer并使用ScheduledThreadPoolExecutor,因为CountDownTimer无法在onTick()取消自己。

出于某种原因,以下代码中的Runnable仅执行一次。我不确定为什么它不会多次执行。 destroyCountdownTimer()功能未受到影响。

private ScheduledThreadPoolExecutor mCountdownTimer;
private Tick mTick;

class Tick implements Runnable {
    @Override
    public void run() {
        Log.e("tick", String.valueOf(mAccumulatedMilliseconds));
        mAccumulatedMilliseconds += 1000;
        populateTimeAccumulated();
        populateTimeRemaining();
        updatePercentages();

        if (mTotalMilliseconds <= mAccumulatedMilliseconds) {
            destroyCountdownTimer();
        }
    }
}

private void startCountdown() {
    if (mAccumulatedMilliseconds < mTotalMilliseconds) {
        mCounterIsRunning = true;

        if (mCountdownTimer == null) {
            mCountdownTimer = new ScheduledThreadPoolExecutor(1);
        }

        if (mTick == null) {
            mTick = new Tick();
        }

        mCountdownTimer.scheduleAtFixedRate(mTick, 1000, 1000, TimeUnit.MILLISECONDS);
    }
}

private void destroyCountdownTimer() {
    if (mCountdownTimer != null) {
        mCountdownTimer.shutdownNow();
        mCountdownTimer = null;
    }

    if (mTick != null) {
        mTick = null;
    }
}

1 个答案:

答案 0 :(得分:4)

documentation说:

If any execution of the task encounters an exception, subsequent executions are suppressed.

将try-catch块添加到Tick runnable。