2

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?

Sam Chen
  • 7,597
  • 2
  • 40
  • 73

1 Answers1

1

The behavior you describe is caused by the asynchronous nature of user interaction. Your two examples can be broken down as follows:

Calling setBase inside onClick

  1. App launches
  2. UI is configured; click listener is set on button
  3. Time passes...
  4. User clicks button
  5. Chronometer baseline is set to the current time
  6. Chronometer is started

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.

Calling setBase inside onCreate and outside onClick

  1. App launches
  2. UI is configured; click listener is set on button
  3. Chronometer baseline is set to the current time
  4. Time passes...
  5. User clicks button
  6. Chronometer is started

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.

stkent
  • 19,772
  • 14
  • 85
  • 111
  • So, `setBase()` does two things, one is setting the base time, and two is setting the start counting point to 0 (internally, also start counting internally), am I right? – Sam Chen Sep 03 '19 at 21:59
  • 1
    Almost! The displayed time will always be a function of ` - `. Therefore, when you set the base time you are resetting the counting point to 0 at exactly the same moment. As current time continues to increase, the counter will count up from 0. – stkent Sep 03 '19 at 22:06