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 ...
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
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.