我希望能够在指定的延迟后调用以下方法。 在objective c中,有这样的东西:

[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5];

在android和java中是否有类似的方法? 例如,我需要能够在5秒后调用一个方法。

public void DoSomething()
{
     //do something here
}

当前回答

如果你使用RxAndroid,那么线程和错误处理就会变得容易得多。以下代码在延迟后执行

Observable.timer(delay, TimeUnit.SECONDS)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(aLong -> {
            // Execute code here
        }, Throwable::printStackTrace);

其他回答

你可以使用新引入的lambda表达式让它更简洁:

new Handler().postDelayed(() -> {/*your code here*/}, time);

类似的解决方案,但使用起来更干净

把这个函数写在类的外面

fun delay(duration: Long, `do`: () -> Unit) {

    Handler().postDelayed(`do`, duration)

}

用法:

delay(5000) {
    //Do your work here
}

你可以在UIThread中使用Handler:

runOnUiThread(new Runnable() {
                
    @Override
    public void run() {
        new Handler().postDelayed(new Runnable() {
           @Override
           public void run() {
               //add your code here
          }
        }, 1000);           
    }
});

如果你使用Android Studio 3.0及以上版本,你可以使用lambda表达式。callMyMethod()方法在2秒后被调用:

new Handler().postDelayed(() -> callMyMethod(), 2000);

如果你需要取消延迟的可运行文件,请使用以下命令:

Handler handler = new Handler();
handler.postDelayed(() -> callMyMethod(), 2000);

// When you need to cancel all your posted runnables just use:
handler.removeCallbacksAndMessages(null);

有很多方法可以做到这一点,但最好的是使用如下处理程序

long millisecDelay=3000

Handler().postDelayed({
  // do your work here
 },millisecDelay)