提问人:Peter Horvath 提问时间:5/10/2022 最后编辑:Peter Horvath 更新时间:5/11/2022 访问量:385
基于 Handler stops、Android、Kotlin 的计时器
Timer based on Handler stops, Android, Kotlin
问:
我用于在 Widget 中创建计时器。
我使用推荐的构造函数,即将 Looper 传递给它。Handler
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 设置为 3000 ms。 计时器运行良好一段时间并执行给定的代码。但是,在随机时间过后,计时器停止工作,并且不再执行给定代码。
请告知问题可能是什么以及如何解决它。 或者,我可以使用其他计时器吗?(计时器应该每隔几秒钟响起一次 - 这就是我使用 Handler 的原因)
提前感谢您的任何建议
答:
0赞
Fedric Antony
5/10/2022
#1
您可以使用 Android 框架来实现相同的目的。它在内部使用 Handler 作为计时器CountDownTimer
val timer = object: CountDownTimer(1000,1000){
override fun onTick(millisUntilFinished: Long) {
}
override fun onFinish() {
}
}
timer.start()
0赞
flamewave000
5/10/2022
#2
你总是可以尝试使用协程来做这样的事情:
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()
}
我还没有测试过上述内容,但它应该工作得很好。
评论
The timer should go off every few second