作为标题,在Kotlin中是否有方法在延迟(例如1秒)后调用函数?


当前回答

我建议使用kotlin协程,如果你想取消它。它结构简单,重量轻。

fun repeatFun(): Job {
    return coroutineScope.launch {  
        while(isActive) {
            //do your work here
            delay(1000)
        }
    }
}

//start the loop
val repeatFun = repeatRequest()

//Cancel the loop
repeatFun.cancel()

其他回答

一个简单的例子来展示3秒后的祝酒词:

fun onBtnClick() {
    val handler = Handler()
    handler.postDelayed({ showToast() }, 3000)
}

fun showToast(){
    Toast.makeText(context, "Its toast!", Toast.LENGTH_SHORT).show()
}
val timer = Timer()
timer.schedule(timerTask { nextScreen() }, 3000)

需要导入以下两个库:

import java.util.*
import kotlin.concurrent.schedule

然后这样使用它:

Timer().schedule(10000){
    //do something
}

很多方面

1. 使用Handler类

Handler().postDelayed({
    TODO("Do something")
    }, 2000)

2. 使用Timer类

Timer().schedule(object : TimerTask() {
    override fun run() {
        TODO("Do something")
    }
}, 2000)

// Shorter

Timer().schedule(timerTask {
    TODO("Do something")
}, 2000)


// Shortest

Timer().schedule(2000) {
    TODO("Do something")
}

3.使用Executors类

Executors.newSingleThreadScheduledExecutor().schedule({
    TODO("Do something")
}, 2, TimeUnit.SECONDS)

如果你正在使用最新的Android api, Handler空构造函数已经被弃用,你应该包括一个循环程序。你可以很容易地通过loop . getmainlooper()得到一个。

    Handler(Looper.getMainLooper()).postDelayed({
        //Your code
    }, 2000) //millis