使用Runnable&更新UI处理程序错误

时间:2011-10-25 18:29:47

标签: android timer handler runnable stopwatch

我正在尝试运行一个计时器,但是当我的计时器启动时,我得到了一个奇怪的错误。它从-214342352:00开始计算。我查看了http://developer.android.com/resources/articles/timed-ui-updates.html,但无法找到我的代码有什么问题。

private Handler mHandler = new Handler();
private long mStartTime = 0L;

启动计时器

if (mStartTime == 0L) {
             mStartTime = System.currentTimeMillis();
             mHandler.removeCallbacks(mUpdateTimeTask);
             mHandler.postDelayed(mUpdateTimeTask, 1000);
}

Runnable

public Runnable mUpdateTimeTask = new Runnable() {
       public void run() {


           final long start =  mStartTime;
           long millis = SystemClock.uptimeMillis()-start;
           int seconds = (int) (millis / 1000);
           int minutes = seconds / 60;
           seconds     = seconds % 60;

           if (seconds < 10) {
              alarmCounter.setText("" + minutes + ":0" + seconds);
           } else {
              alarmCounter.setText("" + minutes + ":" + seconds);            
           }

         //  mHandler.postAtTime(this,start + (((minutes * 60) + seconds + 1) * 1000));
        mHandler.postDelayed(this, 1000);

       }
    };

1 个答案:

答案 0 :(得分:3)

您正在使用两种不同的测量系统。您可以使用SystemClock.uptimeMillis()或使用System.currentTimeMillis()进行所有测量。