android CountDownTimer - last onTick not called - what clean solution to use?

霸气de小男生 提交于 2019-11-30 15:00:17

The behavior you are experiencing is actually explicitly defined in the CountdownTimer code; have a look at the source.

Notice inside of handleMessage(), if the time remaining is less than the interval, it explicitly does not call onTick() and just delays until complete.

Notice, though, from the source that CountdownTimer is just a very thin wrapper on Handler, which is the real timing component of the Android framework. As a workaround, you could very easily create your own timer from this source (less than 150 lines) and remove this restriction to get your final tick callback.

I think the frustration comes from an incorrect expectation of what a tick should be. As the other answer noted, this behavior is intentional. Another possible way of handling this is to simply specify a smaller interval. If you were implementing some sort of countdown clock for example, it wouldn't hurt to change the interval to 500. If it's important that some work is only done when the seconds change, then you can do that too by storing the result of getSeconds() and only doing that work when that value changes.

If CountdownTimer were changed to always fire that last tick even if the remaining time is less than the interval, I'm sure StackOverflow would have a bunch of questions like "why do I not have enough time in the last tick of CountdownTimer?"

Juan Luis Carrasco

I don't understand why you say that it is intentional behaviour, the API says exactly:

"Schedule a countdown until a time in the future, with regular notifications on intervals along the way."

new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
    }

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

if you set the time to 30 seconds, and the countDownInterval to 1000, as the API says regular, it should be fired exactly 30 times. I think it's not an intentional behaviour but a wrong implementation.

The solution should be the one proposed by Sam here:

android CountDownTimer - additional milliseconds delay between ticks

Android's CountDownTimer calls onTick() for the first time as soon as (without delay) the timer is started (as can be seen on line number 93)

Post this, onTick() is called based upon the time remaining until the timer is completed.

If the time remaining until timer completed is less than the time interval specified, then onTick() is not called (line number 136). This is the reason your last onTick() is not being called.

Modified CountDownTimer class

I have modified the timer to call onTick() all intervals (including first and last) after specified delay. Here is the class -

public abstract class CountDownTimer {

    private final long mMillisInFuture;
    private final long mCountdownInterval;
    private long mStopTimeInFuture;

    private boolean mCancelled = false;

    public CountDownTimer(long millisInFuture, long countDownInterval) {
        mMillisInFuture = millisInFuture;
        mCountdownInterval = countDownInterval;
    }

    public synchronized final void cancel() {
        mCancelled = true;
        mHandler.removeMessages(MSG);
    }

    public synchronized final CountDownTimer start() {
        mCancelled = false;
        if (mMillisInFuture <= 0) {
            onFinish();
            return this;
        }
        mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
        onTick(mMillisInFuture);
        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG), mCountdownInterval);
        return this;
    }

    public abstract void onTick(long millisUntilFinished);

    public abstract void onFinish();

    private static final int MSG = 1;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            synchronized (CountDownTimer.this) {
                if (mCancelled)
                    return;
                final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
                if (millisLeft <= 0) {
                    onFinish();
                } else {
                    onTick(millisLeft);
                    sendMessageDelayed(obtainMessage(MSG), mCountdownInterval);
                }
            }
        }
    };
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!