Android StopWatch - 时间越来越快

时间:2012-05-12 11:51:04

标签: android stopwatch

我正在为Android制作秒表应用程序。我有一个启动和停止按钮。我的问题是时间越来越快。我哪里出错了。贝娄是代码:

        final Runnable updater = new Runnable() {

        public void run() {

            if (startIsPressed) {
                time = SystemClock.elapsedRealtime() - initStart + startPointTime;
                startPointTime = time;
            } else {
                time = startPointTime;
            }

            hh = time / 3600000;
            hours.setText("" + formatter.format(hh));
            time = time - hh * 3600000;

            mm = time / 60000;
            minutes.setText("" + formatter.format(mm));
            time = time - mm * 60000;

            ss = time / 1000;
            seconds.setText("" + formatter.format(ss));
            time = time - ss * 1000;

            millis.setText("" + formatter.format(time / 10));

            handler.postDelayed(this, 30);
        }
    };
    startBtn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (!startIsPressed) {
                startIsPressed = true;
                startBtn.setText(R.string.stop);
                initStart = SystemClock.elapsedRealtime();
                handler.post(updater);
            } else {
                startIsPressed = false;
                startBtn.setText(R.string.start);
                handler.post(updater);
            }
        }
    });
}

1 个答案:

答案 0 :(得分:1)

正如文档所述postDelayed导致Runnable r被添加到消息队列中,在指定的时间量过后运行。每1秒更新一次计时器: 使用

handler.postDelayed(this, 100); //100 milliseconds refresh rate

而不是

handler.postDelayed(this, 30); //30 milliseconds refresh rate

并查看秒表逻辑here