我使用简单的CountDownTimer
并且每毫秒调用onTick()
:
final int[] i = new int[1];
CountDownTimer countDownTimer = new CountDownTimer(1000, 1) {
@Override
public void onTick(long millisUntilFinished) {
Log.i("Time left", millisUntilFinished + "");
i[0]++;
}
@Override
public void onFinish() {
Log.i("i = ", i[0] + "");
}
};
问题是虽然计时器在正确的时间内完成,但onTick()
方法并非每毫秒调用一次。每次都会丢失几毫秒。
我使用日志检查了它,发现i[0]
的值最后是597,而它应该是999,因为每次调用onTick()
时它都会+1。有精度错误吗?
答案 0 :(得分:0)
你可以像这样创建处理程序:
Handler timer = new Handler();
timer.postDelayed(new TimerTask() {
@Override
public void run() {
// Make something
}
}, 1000);
答案 1 :(得分:0)
由于主线程上的加载导致somtime跳过一些数字,否则它会完美运行。
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
long durationSeconds=millisUntilFinished/1000;
Log.e("Time","String.format("%02d:%02d", (durationSeconds % 3600) / 60, (durationSeconds % 60))");
}
public void onFinish() {
Log.e("Time Up!","");
}
答案 2 :(得分:0)
尝试使用以下代码:
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
new Handler().post(new Runnable() {
@Override
public void run() {
// To-do
}
});
}
};
timer.schedule(timerTask, 1000, 1000);
答案 3 :(得分:0)
使用处理程序。试试这个:
public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
// We do some logic to respond to launching app, and return to that app.
Task.Delay(500).ContinueWith(_ => {
this.InvokeOnMainThread( () => {
UIApplication.SharedApplication.OpenUrl(NSUrl.FromString(openUri));
});
});
}
首先,将立即调用处理程序。之后,每毫秒都会调用它。