如果在onResume()中恢复计时器,则取消CountDownTimer在onPause()中不起作用

时间:2019-11-22 18:32:47

标签: android kotlin countdowntimer onresume onpause

我正在尝试在onPause()中取消计时器,然后在onResume()中恢复计时器,但是取消无效。计时器仍在后台运行。有人知道为什么吗?

    var currentMillis: Long = 0

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

        override fun onPause() {
                super.onPause()
                timer.cancel()


            }
            override fun onResume() {
                super.onResume()


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

            }

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


        setContentView(R.layout.activity_app)



timer.start()

编辑:

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

            override fun onFinish() {}
        }
    }
    else
    {
        timer?.cancel()
        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()
    i++

0 个答案:

没有答案