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

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

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

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

当前回答

在我的例子中,我不能用其他答案。 我使用本机java定时器代替。

new Timer().schedule(new TimerTask() {          
    @Override
    public void run() {
        // this code will be executed after 2 seconds       
    }
}, 2000);

其他回答

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

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

在我的例子中,我不能用其他答案。 我使用本机java定时器代替。

new Timer().schedule(new TimerTask() {          
    @Override
    public void run() {
        // this code will be executed after 2 seconds       
    }
}, 2000);

以下是我的最短解决方案:

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        //Do something after 100ms
    }
}, 100);

芬兰湾的科特林 从一个片段运行onuithread 计时器

例子:

Timer().schedule(500) {
    activity?.runOnUiThread {
        // code                                    
    }
}

我更喜欢使用View.postDelayed()方法,下面是简单的代码:

mView.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Do something after 1000 ms
    }
}, 1000);