I found that if I call start()
right after setBase(SystemClock.elapsedRealtime())
it will start counting from 00:00 (which is fine), see below:
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
}
});
However, if I place the setBase(SystemClock.elapsedRealtime())
out of the setOnCLickListener()
like this:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chronometer = findViewById(R.id.main_chronometer);
startButton = findViewById(R.id.main_start_button);
resetButton = findViewById(R.id.main_reset_button);
chronometer.setBase(SystemClock.elapsedRealtime()); //no good here
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
}
});
}
It will start counting from the elapsed time since this app launches. Why?
The behavior you describe is caused by the asynchronous nature of user interaction. Your two examples can be broken down as follows:
setBase
inside onClick
Notice there is no time passing between steps 5 (chronometer baseline is set) and 6 (chronometer is started), which is why the chronometer correctly starts at 0 when you check its value.
setBase
inside onCreate
and outside onClick
In this version, time passes between steps 3 (chronometer baseline is set) and 6 (chronometer is started), which is why the chronometer does not start at 0 when you check its value.