Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Start Chronometer from 00:00

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();
        }
    });

 }
}
like image 936
liav bahar Avatar asked Sep 18 '15 11:09

liav bahar


2 Answers

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,

like image 145
Blackbelt Avatar answered Nov 14 '22 06:11

Blackbelt


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();
like image 29
Ajit Kumar Dubey Avatar answered Nov 14 '22 07:11

Ajit Kumar Dubey