Search code examples
androidkotlincountdowntimer

How to resume CountDownTimer?


I can successfully stop timer by using cancel() (timer.cancel()) function. But how to resume it? I searched a lot for various codes but everything was in Java. I need it in Kotlin. Can you give me suggestions? I use code:

val timer = object : CountDownTimer(60000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            textView3.text = (millisUntilFinished / 1000).toString() + ""
            println("Timer  : " + millisUntilFinished / 1000)
        }

        override fun onFinish() {}
    }

Edited:

In Class:

var currentMillis: Long = 0 // <-- keep millisUntilFinished

    // First creation of your timer
    var timer = object : CountDownTimer(60000, 1000) {
        override fun onTick(millisUntilFinished: Long) {

            currentMillis = millisUntilFinished // <-- save value

            textView3.text = (millisUntilFinished / 1000).toString() + ""
            println("Timer  : " + millisUntilFinished / 1000)
        }

        override fun onFinish() {}
    }

In onCreate():

  timer.start()

            TextView2.setOnClickListener {
                //Handle click
                timer.cancel()

            }

            TextView3.setOnClickListener {
                //Handle click
                timer = object : CountDownTimer(currentMillis, 1000) {
                    override fun onTick(millisUntilFinished: Long) {
                        currentMillis = millisUntilFinished
                        textView3.text = (millisUntilFinished / 1000).toString() + ""
                        println("Timer  : " + millisUntilFinished / 1000)
                    }

                    override fun onFinish() {}
                }
            timer.start()
}

Solution

  • My suggestion : keep the millisUntilFinished value and use it for recreating CountDownTimer

    
    var currentMillis: Long // <-- keep millisUntilFinished
    
    // First creation of your timer
    var timer = object : CountDownTimer(60000, 1000) {
       override fun onTick(millisUntilFinished: Long) {
    
         currentMillis = millisUntilFinished // <-- save value
    
         textView3.text = (millisUntilFinished / 1000).toString() + ""
         println("Timer  : " + millisUntilFinished / 1000)
       }
    
       override fun onFinish() {}
       }
    }
    
    ...
    
    // You start it
    timer.start()
    
    ...
    
    // For some reasons in your app you pause (really cancel) it
    timer.cancel()
    
    ...
    
    // And for reasuming
    timer = object : CountDownTimer(currentMillis, 1000) {
       override fun onTick(millisUntilFinished: Long) {
         currentMillis = millisUntilFinished
         textView3.text = (millisUntilFinished / 1000).toString() + ""
         println("Timer  : " + millisUntilFinished / 1000)
       }
    
       override fun onFinish() {}
       }
    }