我希望等待2到3秒钟,我知道在Java中该如何实现并已尝试过,但不清楚如何在Kotlin中实现。
类似以下简单的示例:
println("hello")
// a 2 seconds delay
println("world")
很简单,只需使用协程。就像这样:
fun main() = runBlocking {
launch {
delay(2000L)
println("World!")
}
println("Hello")
}
别忘了像这样导入Kotlin协程:
import kotlinx.coroutines.*
在Kotlin中愉快地编程!!!
有一些方法:
1- 使用Handler(基于毫秒)(已弃用):
println("hello")
Handler().postDelayed({
println("world")
}, 2000)
2- 通过使用 Executors(基于第二种方法):
println("hello")
Executors.newSingleThreadScheduledExecutor().schedule({
println("world")
}, 2, TimeUnit.SECONDS)
3- 通过使用基于毫秒的计时器:
println("hello")
Timer().schedule(2000) {
println("world")
}
使用:
viewmodelScope.launch {
println("hello")
delay(2000)
println("world")
}
如果您不想使用任何依赖项,那么可以使用Thread.sleep(2000L)
。
这里,1秒=1000L
代码应该像这样:
println("hello")
Thread.sleep(2000L)
println("world")