定时器基于Handler停止,Android, Kotlin



我使用Handler在Widget中创建计时器。我使用推荐的构造函数,即传递一个loop给它。

private val updateHandler = Handler(Looper.getMainLooper())
@RequiresApi(Build.VERSION_CODES.Q)
private val runnable = Runnable {
updateDisplay()
}
@RequiresApi(Build.VERSION_CODES.Q)
private fun updateDisplay () {
updateHandler?.postDelayed(runnable, TIMER_MS)
// some other code
}

TIMER MS设置为3000ms。计时器会正常运行一段时间,并执行给定的代码。然而,经过一段随机时间后,计时器停止工作,不再执行给定的代码。

请告知问题可能是什么以及如何解决它。或者,我可以使用其他计时器吗?(计时器应该每隔几秒关闭-这就是我使用Handler的原因)

感谢您提前提出的建议

你可以尝试使用协程来做这样的事情:

class TimedRepeater(var delayMs: Long,
var worker: (() -> Unit)) {
private var timerJob: Job? = null

suspend fun start() {
if (timerJob != null) throw IllegalStateException()
timerJob = launch {
while(isActive) {
delay(delayMs)
worker()
}
}
}
suspend fun stop() {
if (timerJob == null) return
timerJob.cancelAndJoin()
timerJob = null
}
}
suspend fun myStuff() {
val timer = Timer(1000) {
// Do my work
}
timer.start()
// Some time later
timer.stop()
}

我还没有测试过上面的代码,但是它应该可以很好地工作。

您可以使用Android框架中的CountDownTimer来实现相同的功能。它内部使用Handler定时器

val timer = object: CountDownTimer(1000,1000){
override fun onTick(millisUntilFinished: Long) {

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

最新更新