Kotlin中如何设置延迟?

ton*_*nga 7 android kotlin

我只想等 2 或 3 秒,我知道如何在 Java 中做到这一点并且我尝试过,但不知道 kotlin

简单的事情,比如:

println("hello")
// a 2 seconds delay
println("world")
Run Code Online (Sandbox Code Playgroud)

小智 14

这很简单。只需使用协程即可。像这样:

fun main() = runBlocking { 
    launch { 
        delay(2000L)
        println("World!") 
    }
    println("Hello")
}
Run Code Online (Sandbox Code Playgroud)

不要忘记像这样导入 kotlin 协程:

import kotlinx.coroutines.*
Run Code Online (Sandbox Code Playgroud)

祝您在 kotlin 中编码愉快!


soh*_*ari 6

有一些方法:

1-使用Handler(基于毫秒)(已弃用):

println("hello")
Handler().postDelayed({
   println("world")
}, 2000)
Run Code Online (Sandbox Code Playgroud)

2-通过使用执行器(基于第二个):

println("hello")
Executors.newSingleThreadScheduledExecutor().schedule({
    println("world")
}, 2, TimeUnit.SECONDS)
Run Code Online (Sandbox Code Playgroud)

3-通过使用计时器(基于毫秒):

println("hello")
Timer().schedule(2000) {
  println("world")
}
Run Code Online (Sandbox Code Playgroud)