Android上的计时器有一定程度的容差。例如使用Handler的postDelayed()方法:
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
// TODO: do something
handler.postDelayed(this, delayMillis);
}
};
handler.postDelayed(runnable, delayMillis);
上述代码中,run()方法中的代码执行时间并不会精确等于delayMillis,可能会有一定的时间差。因此,如果需要在精确时间点执行代码,可以将容差值减去执行代码的耗时:
long startTime = System.currentTimeMillis();
// do something that takes time
long endTime = System.currentTimeMillis();
long timeDiff = endTime - startTime;
handler.postDelayed(this, delayMillis - timeDiff);