9

When I click on the Image Button(that should start the Chronometer ) the Chronometer doesnt start from 00:00 , but from the time the app is running . For example if I open the app and wait 10 sec , when I'll click on the Imageutton then the Chronometer will strat from 00:10 .. What should I do in order to start the Chronometer from 00:00 whenever i click on the image button ?

Here is my code:

import android.app.Activity;
import android.os.Bundle; 
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.os.SystemClock;

public class MainScreen extends Activity {
    Chronometer focus;
    ImageButton start;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main_screen);

    start=(ImageButton)findViewById(R.id.FingerStartImageBtn);
    focus=(Chronometer)findViewById(R.id.timer);
    focus.setBase(SystemClock.elapsedRealtime());
    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            focus.start();
        }
    });

 }
}
Darek Kay
  • 15,827
  • 7
  • 64
  • 61
liav bahar
  • 237
  • 3
  • 7
  • 13

2 Answers2

14

Calling focus.setBase(SystemClock.elapsedRealtime()) just before calling focus.start(); should do it. From the code of Chronometer

public void setBase(long base) {
    mBase = base;
    dispatchChronometerTick();
    updateText(SystemClock.elapsedRealtime());
}

 private synchronized void updateText(long now) {
    long seconds = now - mBase;
    seconds /= 1000;
    String text = DateUtils.formatElapsedTime(mRecycle, seconds);

as you can see the time is set to 0,

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
10

You can give it a start time in the elapsedRealtime().

I am using below code working fine when I click on button it start from 00:00 and also you can set format like "H:MM:SS" by using

mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
Ajit Kumar Dubey
  • 1,383
  • 1
  • 19
  • 33