I have the following CountDownTimer
:
countdown = new CountDownTimer(10000, 5000) {
@Override
public void onTick(long millisUntilFinished) {
// Stuff here
}
@Override
public void onFinish() {
// Restart countdown
countdown.start();
}
}.start();
As seen, there's a 5 seconds tick interval. But when this CountDown
starts, the first interval occurs at 0 miliseconds.
Why my first tick is being fired at 0 miliseconds time, instead of 5000 miliseconds time?
All the documentation has to say about onTick()
is "Callback fired on regular interval."
http://developer.android.com/reference/android/os/CountDownTimer.html#onTick(long)
Why are you assuming it shouldn't fire immediately?
If want to ignore the first callback to onTick()
you could add a boolean flag like so:
countdown = new CountDownTimer(10000, 1000) {
private boolean first = true;
@Override
public void onTick(long millisUntilFinished) {
if (first) {
first = false;
return;
}
// Stuff here
}
@Override
public void onFinish() {
// Restart countdown
first = true;
countdown.start();
}
}.start();
After looking at your usage of CountDownTimer
a bit more it seems like you could also use a Handler
/ Runnable
combination.
Here's an example:
In your Activity
you do:
private Handler timerHandler;
private Runnable timerRunnable;
// ...
@Override
public void onCreate() {
super.onCreate();
timerHandler = new Handler();
timerRunnable = new Runnable() {
@Override
public void run() {
// Stuff here
timerHandler.postDelayed(timerRunnable, 5000);
}
};
timerHandler.postDelayed(timerRunnable, 5000);
}