Android倒计时器逐渐失去时间

时间:2012-03-04 09:15:39

标签: android timer countdown

我正在尝试创建一个针对平板电脑优化的倒数计时器,除了随着时间的推移逐渐失去时间的细微细节之外它运行正常:超过5分钟它在我的Xoom上测试时可能会损失1-2秒

这是我的onTick代码:

        public void onTick(long millisUntilFinished) {
        // TODO Auto-generated method stub
        currentTime = System.currentTimeMillis();
        currentCount = startTime - currentTime;
        //currentCount = millisUntilFinished;
        displayCorrectTime();
    }

最初,我开始只使用'millisUntilFinished',当我注意到时间正在滑落时。然后,我阅读并尝试通过使用开始时间和“现在”之间的差异来更好地同步,以通知计时器。不幸的是,这两种方法似乎都浪费了时间(我真的不明白第二种方法如何浪费时间,但仍然如此)。

有什么建议吗?

3 个答案:

答案 0 :(得分:0)

这是正常的,System.currentTimeMillis()有准确性。您可以尝试System.nanoTime()获得(理论上)更好的精度。无论如何,您需要补偿执行displayCorrectTime()调用所需的时间。

更好的解决方案是使用:

http://developer.android.com/reference/java/util/Timer.html

答案 1 :(得分:0)

new CountDownTimer(60000, 1000) { 
        long startTime = System.currentTimeMillis();
        public void onTick(long millisUntilFinished) {
            long timePassed = System.currentTimeMillis() - startTime;
            pb.setProgress(60000-(int)timePassed);
            t.setText(String.valueOf((60000-timePassed)/1000));
        }

        public void onFinish() {
            Intent intent = new Intent(GameActivity.this, SummaryActivity.class);
            startActivity(intent);
        }
    }.start();

这对我有用。这是一个1分钟的倒计时器,带有进度条显示。

答案 2 :(得分:0)

这是我很久以前为Java服务器应用编写的一个简单函数:

/// <summary>
/// A static helper class the enables a thread to sleep for a specific period of
/// time, manage drift and supports clock changes.
/// </summary>
public static class ThreadHelper
{
    /// <summary>
    /// Enables a thread to sleep for a specific period of time, manage drift and
    /// supports clock changes. This function enables the user to break from the
    /// call.
    /// </summary>
    /// <param name="startTicks">A long value that specifies the time to start sleeping.</param>
    /// <param name="intervalTicks">The long value that specifies the duration to sleep for.</param>
    /// <param name="signalStop">A reference to a bool that enables the caller to
    /// break out of this call from another thread.</param>
    /// <returns>A long value that specifies the value the caller should use for the
    /// startTicks parameters on subsequent calls into this function.</returns>
    public static long Sleep(long startTicks, long intervalTicks, ref bool signalStop)
    {
        long finalTicks = startTicks + intervalTicks;

        while (finalTicks + intervalTicks < DateTime.Now.Ticks)
        {
            finalTicks += intervalTicks;
        }

        while (!signalStop && DateTime.Now.Ticks < finalTicks)
        {
            while (finalTicks - intervalTicks > DateTime.Now.Ticks)
            {
                finalTicks -= intervalTicks;
            }

            Thread.Sleep(1000);
        }
        return finalTicks;
    }
}