触发onStop时,设置为20秒的Timer()fixedRateTimer不会停止

时间:2019-11-23 16:43:16

标签: android kotlin timer kotlin-coroutines

我将计时器设置为在活动进行时每20秒获取一个时间戳。 它正确注册了时间,但是当我的Activity的onStop方法被触发时,它将继续运行。我已确认onStop已触发,但计时器将永远继续。这是我的活动中的内容:

private lateinit var timer: Timer


override fun onStart() {
    super.onStart()
    checkForUpdates(true)
}

override fun onStop() {
    super.onStop()
    println("super.onStop triggered")
    checkForUpdates(false)
    timer.cancel()
    timer.purge()
}

private fun checkForUpdates(daemonIsTrue: Boolean) {
        timer = fixedRateTimer("default", daemonIsTrue, 0L, 20000) {
            Coroutines.io {
                val dateStamp = DateTime(DateTimeZone.UTC).toString("YYYY-MM-dd HH:mm:ss")
                println("dateStamp at $dateStamp")  
            }
        }
    }
}

这是我的协程扩展程序,以防万一:

object Coroutines{
    fun io(work: suspend (() -> Unit)) =
            CoroutineScope(Dispatchers.IO).launch {
                work()
            }
}

有人可以帮我弄清楚如何正确停止此计时器吗?

1 个答案:

答案 0 :(得分:1)

您正在通过两个Timer调用创建两个checkForUpdates()对象,而您只取消了第二个。也许摆脱checkForUpdates()中的onStop()调用。