Home > Software design >  Timer reset when fragment is destroyed
Timer reset when fragment is destroyed

Time:10-07

I want to recreate a timer like Google Authenticator, which never stops and if the app is killed and you reopen it, the timer still working.

I tried to make a timer but every time I destroy the fragment, it resets. How it is possible to do this?

val timer = object: CountDownTimer(10000,1000){
   override fun onTick(millisecondsLeft:Long){
      //Do something
   }
   override fun onFinish(){
      this.start //this resets the timer when it reach 0
   }
}
timer.start()

CodePudding user response:

It's not a timer. It simply uses realtime clock.

The "start" event is that you take the current RTC value, save it and then display the difference as "elapsed time". This way, there is nothing to worry about when the app is not running. On app restart, re-read the value and you're there.

CodePudding user response:

Keep your timer in a ViewModel, which is Lifecycle aware, so your timer will keep working as long as the parent activity "exists".

class YourViewModel: ViewModel() {
    
    private val timer: CountDownTimer
    
    init {
        timer = object: CountDownTimer(10000, 1000) {
            override fun onTick(p0: Long) {
                //Do something
            }
            
            override fun onFinish() {
                this.start() //this resets the timer when it reach 0
            }
        }
    }
    
    override fun onCleared() {
        super.onCleared()
        timer.cancel()
    }
}
  • Related