我是 kotlin 的初学者。我尝试创建一个每 2 秒重复一次的任务。所以我创造了这样的东西。
val handler = Handler()
handler.postDelayed(Runnable {
// TODO - Here is my logic
// Repeat again after 2 seconds
handler.postDelayed(this, 2000)
}, 2000)
但是在 postDelayed(this) 中它给出了错误 -
required Runnable!, found MainActivity
.我什至尝试过this@Runnable
但它没有用。但是当我像这样编写相同的函数时,它可以工作
val handler = Handler()
handler.postDelayed(object : Runnable {
override fun run() {
// TODO - Here is my logic
// Repeat again after 2 seconds
handler.postDelayed(this, 2000)
}
}, 2000)
那么为什么
this
关键字在第一个功能中不起作用,但在第二个功能中效果很好?
最佳答案
您有几种选择:
//class scope
val handler = Handler()
val runnable = object : Runnable {
override fun run () {
handler.removeCallbacksAndMessages(null)
//make sure you cancel the
previous task in case you scheduled one that has not run yet
//do your thing
handler.postDelayed(runnable,time)
}
}
然后在某些功能中
handler.postDelayed(runnable,time)
timertask
, 在这种情况下会更好 val task = TimerTask {
override fun run() {
//do your thing
}
}
val timer = Timer()
timer.scheduleAtFixedRate(task,0L, timeBetweenTasks)
关于android - Kotlin - 如何在 Handler 中传递一个 Runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60761647/