循环一秒钟

Nat*_*May 2 java android timing

我正在尝试创建一个Android应用程序,每秒记录一个跑步者的位置.但是,我发现它完成后需要稍微超过一秒钟.

这是我的代码:

Runnable run = new Runnable() {
    @Override
    public void run() {
        Long start = SystemClock.elapsedRealtime();
        if (getIfRunning() == true) {
            try {
                if (location2 != null) {
                    Float distanceFromLast = totalDistance(location2);
                    addToDistance(distanceFromLast);
                }
                getCoords();
                mMap.clear();
                markOldCoords();
                writeCoords();
                setCount();
                updateScreen();
            } catch (Exception e) {
            }
        }
        Long time = SystemClock.elapsedRealtime() - start;
        handler.postDelayed(this, 1000 - time);
    }
};
handler.post(run);
Run Code Online (Sandbox Code Playgroud)

AlB*_*lue 5

一般来说,你不能得到这样的确切时间.由于当时系统正在做什么,定时器总是会稍早或稍晚醒来.您可以做的最好的事情就是接受它永远不会是完美的并相应地更新您的代码以找出您实际触发的时间.