How to resume CountDownTimer?

梦想与她 提交于 2019-12-24 21:54:27

问题


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()
}

回答1:


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() {}
   }
}


来源:https://stackoverflow.com/questions/58944590/how-to-resume-countdowntimer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!