2

I am trying to implement a chronometer with hour minute and seconds format. when I call stop the chronometer still keeps counting the time and gets added to it once I start the chronometer again. I also don't want the chronometer to be reset, thereby only resume it.

This is my code :

on create :

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

chronometer method:

 @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);
    }

1 Answers1

2

As you can read on documentation

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

So you have to reset the base of your chronometer. On your start button do:

        ((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();
            }
        });

If you want to pause e resume your chronometer you have to keep track of the time elapsed from pause click and then set the correct base on 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();
    }
});
appersiano
  • 2,670
  • 22
  • 42
  • but doing that will only reset it. I don't want to reset the chrono though only pause it then resume – BlueDaBaDee Feb 02 '17 at 16:11
  • 2
    Your second edit was useful, I was relying on my time variable that was updated onChronometerTick, no wonder my timer also went to negative counting upto zero and then incremented starting from 0. Thanks a lot for your time have a nice day :) – BlueDaBaDee Feb 02 '17 at 16:47