title: Android keep the stopwatch running
body: <p>I am developing right now a countdown timer. But I want it to be running even when I would go back to the previous activity. How could I achieve this? Android newbie here.</p>
  
  <p>This is what I've done so far:
          private Button pause, stop, start, reset;
      private Chronometer chronometer;
      long timeWhenStopped = 0;</p>
  
  <pre><code>@Override
  protected void onCreate(Bundle savedInstanceState) {
      // TODO Auto-generated method stub
      super.onCreate(savedInstanceState);
      requestWindowFeature(Window.FEATURE_LEFT_ICON);
      setContentView(R.layout.stopwatch);
      getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.clock32);
  
      // initializes controls
      initControls();
  
      // sets format for chronometer
      chronometer.setText( "00:00:00" );
  
  }
  
  
  private void initControls(){
  
      // initializes buttons &amp; chronometer
      pause = ( Button ) findViewById ( R.id.btStopWatchPause );
      stop = ( Button ) findViewById ( R.id.btStopWatchStop );
      start = ( Button) findViewById ( R.id.btStopWatchStart );
      reset = ( Button ) findViewById ( R.id.btStopWatchReset );
      chronometer = ( Chronometer ) findViewById ( R.id.chronometer );
  
      // sets listeners for buttons and chronometer
      pause.setOnClickListener(this);
      stop.setOnClickListener(this);
      start.setOnClickListener(this);
      reset.setOnClickListener(this);
      chronometer.setOnChronometerTickListener(this);
  
  }
  
  
  public void onClick(View v) {
      // TODO Auto-generated method stub
  
      switch( v.getId() )
      {
      case R.id.btStopWatchStart:
          chronometer.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
          chronometer.start();
          break;
      case R.id.btStopWatchStop:
          chronometer.stop();
          break;
      case R.id.btStopWatchReset:
          chronometer.setBase(SystemClock.elapsedRealtime());
          break;
      case R.id.btStopWatchPause:
          timeWhenStopped = chronometer.getBase() - SystemClock.elapsedRealtime();
          chronometer.stop();
          break;
  
      } // end of switch statement
  
  }
  
  public void onChronometerTick(Chronometer c) {
      // TODO Auto-generated method stub
  
      CharSequence text = c.getText();
      if ( text.length()  == 5 ) {
          c.setText( "00:" + text );
      } else if ( text.length() == 7 ) {
          c.setText( "0" + text );
      }
  
  
  
  } // end of onChronometerTick method
  </code></pre>