Search code examples
javaandroidandroid-studiochronometer

Android - Chronometer setBase() doesn't work properly


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?


Solution

  • 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.