chronometer resume?

peace picture peace · Oct 11, 2012 · Viewed 6.9k times · Source

when I clicked start, the 'stopwatch' started to count.. I pressed pause, only the textview paused, it's not resuming, because it still running in background.. I need it to be resumed at where I've stopped..

here's my dot java code :

package com.example.chronometer2;

import com.example.chronometer.R;

import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;

public class ChronometerApp extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_chronometer);

       final Chronometer myChronometer = (Chronometer)findViewById(R.id.my_chronometer);
       Button buttonStart = (Button)findViewById(R.id.buttonstart);
       Button buttonStop = (Button)findViewById(R.id.buttonstop);
       Button buttonReset = (Button)findViewById(R.id.buttonreset);

       buttonStart.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    myChronometer.start();
   }});

       buttonStop.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    myChronometer.stop();

   }});

       buttonReset.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    myChronometer.setBase(SystemClock.elapsedRealtime());

   }});

   }
}

Answer

fabzy picture fabzy · Oct 11, 2012

You need to define a variable which contains the elapsed time when the chronometer was stopped

timeWhenStopped = chronometer.getBase() - SystemClock.elapsedRealtime();

and then when you start again set the the timer plus the timeWhenStopped

chronometer.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);

to reset the chronometer just use

chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.stop();
timeWhenStopped = 0;

and maybe you need to add an extra variable to define if the chronometer is running