【发布时间】:2022-11-02 20:03:41
【问题描述】:
我构建了一个安卓应用倒计时器使用科特林。当我使用启动计时器时协程它会引发如下错误。
需要您的帮助:
- 如何处理或实现倒数计时器的处理程序,该处理程序将在不同的设备上运行 线程而不是主线程...或者...如何使用 kotlin 协程实现计时器?
错误文本:
java.lang.RuntimeException: Can't create handler inside thread Thread[DefaultDispatcher-worker-1,5,main] that has not called Looper.prepare()
代码:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnStartPause.setOnClickListener {
if (isRunning) {
pauseTimer()
} else {
val time = edtTxtTimer.text.toString().trim()
timeInMilliSeconds = time.toLong() * 60000L // 1m = 60,000ms
CoroutineScope(Dispatchers.Default).launch {
startTimer(timeInMilliSeconds)
}
}
}
}
////////////////////////////////////////////////////
////////////////////////////////////////////////////
private fun startTimer(time_in_milli_second: Long) {
countdown_timer = object : CountDownTimer(time_in_milli_second, 1000) {
override fun onTick(millisUntilFinished: Long) {
timeInMilliSeconds = millisUntilFinished
updateUI()
}
override fun onFinish() {
btnStartPause.text = "Start"
loadConfeti()
}
}
countdown_timer.start()
isRunning = true
btnStartPause.text = "Pause"
btnReset.visibility = View.GONE
}
【问题讨论】:
标签: android kotlin kotlin-coroutines countdowntimer android-handler