android CountDownTimer - last onTick not called -

2020-02-29 03:11发布

frustration post ....

I just stumbled into the "CountDownTimer - last onTick not called" problem many have reported here.

Simple demo showing the problem

package com.example.gosh;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;

public class CountDownTimerSucksActivity extends Activity {

int iDontWantThis = 0; // choose 100 and it works yet ...

private static final String TAG = "CountDownTimerSucksActivity";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    new MyCountDownTimer(10000 + iDontWantThis , 1000).start();
}

class MyCountDownTimer extends CountDownTimer {

    long startSec;

    public MyCountDownTimer(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        // TODO Auto-generated constructor stub
        startSec = System.currentTimeMillis() ;
    }

    @Override
    public void onFinish() {
        // TODO Auto-generated method stub
        Log.e(TAG, " onFinish (" + getSeconds() + ")");
    }

    @Override
    public void onTick(long millisUntilFinished) {
        // TODO Auto-generated method stub
        Log.e(TAG, millisUntilFinished + " millisUntilFinished" + " (" + getSeconds() + ")");

    }

    protected long getSeconds() {
        return  (((System.currentTimeMillis() - startSec) / 1000) % 60);

    }

}

}

The logcat output from a test run ...

logcat ouput

As you can see the last call onTick is happening with 1963ms millisUntilFinished, then the next call is onFinished nearly 2 seconds later. Surely a buggy behavior. I found many posts on this yet no clean solution yet. One I included in the source code, if you set the iDontWantThis field to 100 it works.

I dont mind workarounds in minor fields yet this seems such a core functionality that i cant fathom it wasnt fixed yet. What are you people doing to have a clean solution for this?

Thanks a lot

martin

UPDATE:

A very useful modification of the CountDownTimer by Sam which does not surpresses the last tick due to internal ms delay and also prevents the accumulation of ms delay with each tick over time can be found here

4条回答
做自己的国王
2楼-- · 2020-02-29 03:30

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?"

查看更多
太酷不给撩
3楼-- · 2020-02-29 03:42

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);
                }
            }
        }
    };
}
查看更多
成全新的幸福
4楼-- · 2020-02-29 03:43

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.

查看更多
Deceive 欺骗
5楼-- · 2020-02-29 03:46

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

查看更多
登录 后发表回答