我希望能够在指定的延迟后调用以下方法。 在objective c中,有这样的东西:
[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5];
在android和java中是否有类似的方法? 例如,我需要能够在5秒后调用一个方法。
public void DoSomething()
{
//do something here
}
我希望能够在指定的延迟后调用以下方法。 在objective c中,有这样的东西:
[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5];
在android和java中是否有类似的方法? 例如,我需要能够在5秒后调用一个方法。
public void DoSomething()
{
//do something here
}
当前回答
类似的解决方案,但使用起来更干净
把这个函数写在类的外面
fun delay(duration: Long, `do`: () -> Unit) {
Handler().postDelayed(`do`, duration)
}
用法:
delay(5000) {
//Do your work here
}
其他回答
好吧,如果你使用Java,你总是可以使用遗留的Thread.sleep()。
new Thread(() -> {
try {
Thread.sleep(millis); //delay in milliseconds
} catch (Exception e) {
e.printStackTrace();
}
yourMethod();
}).start();
这里唯一的问题是你不能做任何UI更新,因为它是一个单独的线程。
使用CountDownTimer非常简单。 详情https://developer.android.com/reference/android/os/CountDownTimer.html
import android.os.CountDownTimer;
// calls onTick every second, finishes after 3 seconds
new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
Log.d("log", millisUntilFinished / 1000);
}
public void onFinish() {
// called after count down is finished
}
}.start();
你可以使用新引入的lambda表达式让它更简洁:
new Handler().postDelayed(() -> {/*your code here*/}, time);
芬兰湾的科特林 从一个片段运行onuithread 计时器
例子:
Timer().schedule(500) {
activity?.runOnUiThread {
// code
}
}
以下是我的最短解决方案:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);