Search code examples
javaandroidtimecountdowntimer

How to keep timer running when closing the app?


i have code like this , i wanna make timer keep running when i close the app.

private void startStop() {
    if (timerStatus == TimerStatus.STOPPED) {
        setTimerValues();
        setProgressBarValues();
      timerStatus = TimerStatus.STARTED; startCountDownTimer();

    } else {
        timerStatus = TimerStatus.STOPPED;
        stopCountDownTimer();

    }
}

Solution

  • Assuming you want something like starting the timer, see the progress bar move and if you come back to your app after an hour, it should have advanced by that time.

    The easiest approach would be to store the time at which the timer was started in a shared preference and update your timer periodically using System.currentTimeMillis()-startTime

    All left to do is restore the shared preference in your Activity's onCreate