ScheduledThreadPoolExecutor 仅 "ticking" 一次
ScheduledThreadPoolExecutor only "ticking" once
我在 Activity
中使用 CountDownTimer
来实现一些倒计时功能。我决定离开 CountDownTimer
并使用 ScheduledThreadPoolExecutor
因为 CountDownTimer
s 无法在 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;
}
}
If any execution of the task encounters an exception, subsequent executions are suppressed.
将 try-catch 块添加到您的 Tick runnable。
我在 Activity
中使用 CountDownTimer
来实现一些倒计时功能。我决定离开 CountDownTimer
并使用 ScheduledThreadPoolExecutor
因为 CountDownTimer
s 无法在 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;
}
}
If any execution of the task encounters an exception, subsequent executions are suppressed.
将 try-catch 块添加到您的 Tick runnable。