调用 stop 后计时器仍然是 运行?

Chronometer is still running after calling stop?

我正在尝试实现一个时分秒格式的计时器。当我打电话给停止时,计时器仍然会继续计算时间,并在我再次启动计时器后添加到它。我也不希望计时器被重置,因此只能恢复它。

这是我的代码:

创建时:

Chronometer myChronometer;
long time;
myChronometer =(Chronometer) findViewById(R.id.chronometer);
        myChronometer .setOnChronometerTickListener(this);
        myChronometer .setBase(SystemClock.elapsedRealtime()+time);

计时法:

 @Override
    public void onChronometerTick(Chronometer cArg) {
       time = SystemClock.elapsedRealtime() - cArg.getBase();

        int h   = (int)(time /3600000);
        int m = (int)(time - h*3600000)/60000;
        int s= (int)(time - h*3600000- m*60000)/1000 ;
        String hh = h < 10 ? "0"+h: h+"";
        String mm = m < 10 ? "0"+m: m+"";
        String ss = s < 10 ? "0"+s: s+"";
        cArg.setText(hh+":"+mm+":"+ss);
    }

您可以在文档中阅读

Stop counting up. This does not affect the base as set from setBase(long), just the view display.

所以你必须重置你的计时表的底座。在您的开始按钮上执行:

        ((Button) findViewById(R.id.start)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //THIS RESET YOUR CHRONOMETER BASE
                myChronometer.setBase(SystemClock.elapsedRealtime()); 
                myChronometer.start();
            }
        });

如果你想暂停和恢复你的计时器,你必须跟踪暂停点击后经过的时间,然后在开始时设置正确的基准:

long timeWhenStopped;

((Button) findViewById(R.id.start)).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        myChronometer.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
        myChronometer.start();
    }
});

((Button) findViewById(R.id.stop)).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        myChronometer.stop();
        timeWhenStopped = myChronometer.getBase() - SystemClock.elapsedRealtime();
    }
});