chronometer doesn't stop in android

Siva K picture Siva K · Apr 21, 2011 · Viewed 10.1k times · Source

In my app I want to show a stop timer watch. When I searched through Google I found an option called Chronometer in the developers site. It look's just like a stop timer watch.

When I click the start button I want the timer to get started and when I click the pause button the timer must be paused when once I click the start it must start from the time it's been stopped.

But in this chronometer it get's started from 0 and when I click pause at 1min 10 sec it get paused. When I click once again start after 5min, the timer start the count from 6min 10sec, even at pause the timer is running, how to stop this and get resumed at the time it is been stopped.

Following is my code for chronometer

Start = (Button)findViewById(R.id.widget306);
        Start.setOnClickListener(new View.OnClickListener() 
        {   
            @Override
            public void onClick(View v) 
            {
                chronometer.start();                
            }
        });

        Stop = (Button)findViewById(R.id.widget307);
        Stop.setOnClickListener(new View.OnClickListener() 
        {   
            @Override
            public void onClick(View v) 
            {
                  chronometer.stop();
            }
        });
    }

Answer

realjin picture realjin · Jun 26, 2011

Sorry, but I've found a solution myself and it seems much simpler:

  1. In your activity, declare a member variable(e.g. lastPause) to record the time of your last pause:

    private long lastPause;

  2. Start your timer (assume the variable of your timer is crono):

    crono.setBase(SystemClock.elapsedRealtime());

    crono.start();

  3. Pause your timer each time using:

    lastPause = SystemClock.elapsedRealtime();

    crono.stop();

  4. Resume your timer each time using:

    crono.setBase(crono.getBase() + SystemClock.elapsedRealtime() - lastPause);

    crono.start();

I've not tested the precision precisely yet as it seems to be ok by my eyes :]