Home > Back-end >  CountDownTimer with ProgressBar, continuing progressbar when restarting the app
CountDownTimer with ProgressBar, continuing progressbar when restarting the app

Time:12-04

I have a ProgressBar that shows the progression of a CountdownTimer. The ProgressBar works except for when I close the app and start it again. If I do that, the ProgressBar begins from zero. It doesn't continue where I left off.

I have a variable to maintain the countdown in milliseconds. I manage to maintain it correctly by using SharedPreferences in the OnStop and OnStart methods. But how do I use this variable correctly for maintaining the progress of the ProgressBar?

private fun startCountdown() {

    var i = 1

    object : CountDownTimer(timeLeftInMilliseconds, 1000) {

        override fun onTick(millisUntilFinished: Long) {

            timeLeftInMilliseconds = millisUntilFinished
            
            i  

            myProgressBar.progress = (i * 100 / (40000 / 1000)).toInt()
            //Instead of 40000 here, I have tried to use the variable 
            //timeLeftInMilliSeconds or millisUntilFinished, but that doesn't work. 
        }

        override fun onFinish() {
            progressBarOutOfLikesTimer.progress = 100;
            timeLeftInMilliseconds = 40000
        }
}

CodePudding user response:

I think this i variable is adding unnecessary complication. You can directly calculate the fraction of the bar to fill from the remaining time divided by total time. I use toDouble() here to be sure we aren't doing integer math and getting unwanted truncating. I'm assuming max of the ProgressBar is 100. You should multiply the time fraction by whatever the max is.

private fun startCountdown() {

    object : CountDownTimer(timeLeftInMilliseconds, 1000) {

        override fun onTick(millisUntilFinished: Long) {
            timeLeftInMilliseconds = millisUntilFinished
            myProgressBar.progress = (100 * (1.0 - millisUntilFinished.toDouble() / 40000)).toInt()
        }

        override fun onFinish() {
            progressBarOutOfLikesTimer.progress = 100;
            timeLeftInMilliseconds = 40000
        }
}
  • Related