我希望能够在指定的延迟后调用以下方法。 在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);

其他回答

我建议使用定时器,它允许你在特定的时间间隔内安排一个方法被调用。这将不会阻塞你的UI,并保持你的应用程序的共鸣,而方法正在执行。

另一个选项是wait();方法,这将阻塞当前线程指定的时间长度。如果你在UI线程上这样做,这将导致你的UI停止响应。

谢谢你的回答,我找到了一个最适合我需要的解决方案。

Handler myHandler = new DoSomething();
Message m = new Message();
m.obj = c;//passing a parameter here
myHandler.sendMessageDelayed(m, 1000);

class DoSomething extends Handler {
    @Override
    public void handleMessage(Message msg) {
      MyObject o = (MyObject) msg.obj;
      //do something here
    }
}

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

long millisecDelay=3000

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

对活动类的另一个响应(java8)。

//hide with delay
new Thread(() -> {
    try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
    this.runOnUiThread(() -> {
        myView.setVisibility(View.GONE);//this run on GUI
    });
}).start();

我创建了一个更简单的方法来调用它。

public static void CallWithDelay(long miliseconds, final Activity activity, final String methodName)
    {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                try {
                    Method method =  activity.getClass().getMethod(methodName);
                    method.invoke(activity);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }, miliseconds);
    }

要使用它,只需调用:.CallWithDelay(5000,这个,"DoSomething");