由于您无法引用当前所在的lambda表达式,也无法在定义属性时引用分配给它的lambda表达式,因此在这里最好的解决方案是对象表达式
:
val runnableCode = object: Runnable {
override fun run() {
handler.postDelayed(this, 5000)
}
}
假设这个属性不是一个var
,因为在这个自调用发生时你实际上想要改变它。
仅需使用fixedRateTimer
fixedRateTimer("timer",false,0,5000){
this@MainActivity.runOnUiThread {
Toast.makeText(this@MainActivity, "text", Toast.LENGTH_SHORT).show()
}
}
通过为第三个参数设置另一个值来更改初始延迟。
时间单位包括:NANOSECONDS(纳秒)、MICROSECONDS(微秒)、MILLISECONDS(毫秒)、SECONDS(秒)、MINUTES(分钟)、HOURS(小时)和DAYS(天)。 示例:Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);
private fun mDoThisJob(){
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate({
//TODO: You can write your periodical job here..!
}, 1, 1, TimeUnit.SECONDS)
}
fun StartTimer() {
Timer_Preview.postDelayed(Runnable { runnable() }, 5000)
}
fun runnable() {
//Code here
// Run code again after 5 seconds
Timer_Preview.postDelayed(Runnable { runnable() }, 5000)
}
然而,在你的特定情况中,看起来你可以只需再次调用StartTimer()
来重新启动计时器,假设它不会执行其他任何操作:
private val RunnableCode = Runnable {
//Code here
//Run code again after 5 seconds
StartTimer()
}
您可以使用简单的函数来实现这个功能:
private fun waitToDoSomethingRecursively() {
handler.postDelayed(::doSomethingRecursively, 5000)
}
private fun doSomethingRecursively () {
...
waitToDoSomethingRecursively()
}
Callable
传递给您的Handler
,并使用sendMessageDelayed
进行递归。 - holi-java