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

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

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

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

当前回答

如果你必须使用处理器,但你在另一个线程中,你可以使用runonuithread在UI线程中运行处理器。这将避免抛出异常请求调用loop . prepare ()

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //Do something after 1 second
            }
        }, 1000);
    }
});

看起来很乱,但这是一种方法。

其他回答

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

把这个函数写在类的外面

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

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

}

用法:

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

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

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

每个人似乎都忘记在发布新的可运行文件或消息之前清理处理程序。否则,它们可能会累积并导致不良行为。

handler.removeMessages(int what);
// Remove any pending posts of messages with code 'what' that are in the message queue.

handler.removeCallbacks(Runnable r)
// Remove any pending posts of Runnable r that are in the message queue.

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

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

使用Kotlin,我们可以通过执行以下操作来实现

Handler().postDelayed({
    // do something after 1000ms 
}, 1000)