gpt4 book ai didi

java - CountDownTimer 值永远不会为零

转载 作者:行者123 更新时间:2023-12-01 09:50:59 25 4
gpt4 key购买 nike

我将计时器初始化为 11000 毫秒,通过日志我看到计时器从 10959 毫秒变为 1484 毫秒

private void startGameCountDown() {
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() {
}
}.start();

这里出了什么问题?

最佳答案

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

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);
}
}
};

}

关于java - CountDownTimer 值永远不会为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37593403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com