Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chronometer doesn't stop in android

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();
            }
        });
    }
like image 597
Siva K Avatar asked Apr 21 '11 06:04

Siva K


3 Answers

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 :]

like image 200
realjin Avatar answered Nov 19 '22 08:11

realjin


From the Chronometer doc

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

I dont have any android dev environment right now, so cant investigate on it more :(

Edit: is it the code you have based your code on ? It seems to use setBase to the current time on stop

like image 2
ccheneson Avatar answered Nov 19 '22 08:11

ccheneson


I faced the same issue and I fixed it by using the following code:

chronometerInstance.setBase(SystemClock.elapsedRealtime());
chronometerInstance.stop();

This is stopped my chronometer counting to 00:00.

like image 1
Bharathi Kasi Avatar answered Nov 19 '22 08:11

Bharathi Kasi