Handler.PostDelayed()对我来说不一致。 1ms和10ms的延迟是相同的,我的项目也需要更小的延迟。我还能使用其他功能吗?谢谢!
答案 0 :(得分:0)
您可以尝试以下方法:
Timer t = new Timer();
t.scheduleAtFixedRate(
new TimerTask() {
@Override
public void run() {
// Your code
cancel(); // For exit to loop
}
}
},
0,
100); // Period: time in milliseconds between successive task executions.
答案 1 :(得分:0)
您可以为此使用Kotlin协程。
摘录自documentation:
import kotlinx.coroutines.*
fun main() {
GlobalScope.launch { // launch a new coroutine in background and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
println("Hello,") // main thread continues while coroutine is delayed
Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
}
您可以循环操作并减少资源消耗:
fun main() = runBlocking {
repeat(100_000) { // launch a lot of coroutines
launch {
delay(1000L)
print(".")
}
}
}
以下文章可能会有所帮助:Kotlin Coroutines — Thread.sleep() vs delay
您还可以考虑使用CountDownTimer