关闭应用程序时如何保持计时器运行?

How to keep timer running when closing the app?

我有这样的代码,我想让计时器在我关闭应用程序时保持 运行。

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

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

    }
}

假设您想要启动计时器之类的东西,看到进度条移动,如果您在一个小时后返回您的应用程序,到那时它应该已经提前了。

最简单的方法是将计时器启动的时间存储在共享首选项中,并使用 System.currentTimeMillis()-startTime

定期更新您的计时器

剩下要做的就是恢复您 Activity 的 onCreate

中的共享首选项