我刚刚遇到了“CountDownTimer - last onTick not called”问题,这是许多人在这里报告的。
这里有一个简单的演示,展示了这个问题。
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);
}
}
}
测试运行中的logcat输出...
正如您所看到的,最后一次onTick调用发生在1963毫秒之后,然后下一次调用将近2秒后的onFinished。这肯定是一个有缺陷的行为。我在许多帖子中找到了这个问题,但还没有干净的解决方案。我在源代码中包含了一个解决方案,如果将iDontWantThis字段设置为100,则可以解决该问题。我不介意在较小的领域使用变通方法,但这似乎是如此核心的功能,以至于我无法想象它尚未修复。你们做了什么来找到一个干净的解决方案?
非常感谢
马丁
更新:
Sam对CountDownTimer进行了非常有用的修改,它不会由于内部毫秒延迟而抑制最后一个tick,并且还可以防止随着时间的推移每个tick累积ms延迟。 在这里 可以找到。