我在我的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;
}
}
答案 0 :(得分:4)
If any execution of the task encounters an exception, subsequent executions are suppressed.
将try-catch块添加到Tick runnable。