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

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

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

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

当前回答

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

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

其他回答

好吧,如果你使用Java,你总是可以使用遗留的Thread.sleep()。

new Thread(() -> {

    try {
        Thread.sleep(millis); //delay in milliseconds
    } catch (Exception e) {
        e.printStackTrace();
    }

    yourMethod();

}).start();

这里唯一的问题是你不能做任何UI更新,因为它是一个单独的线程。

android中合适的解决方案:

private static long SLEEP_TIME = 2 // for 2 second
.
.
MyLauncher launcher = new MyLauncher();
            launcher.start();
.
.
private class MyLauncher extends Thread {
        @Override
        /**
         * Sleep for 2 seconds as you can also change SLEEP_TIME 2 to any. 
         */
        public void run() {
            try {
                // Sleeping
                Thread.sleep(SLEEP_TIME * 1000);
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
            //do something you want to do
           //And your code will be executed after 2 second
        }
    }

在Android中,我们可以编写下面的kotlin代码来延迟任何函数的执行

class MainActivity : AppCompatActivity() {

private lateinit var handler: Handler

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    handler= Handler()
    handler.postDelayed({
        doSomething()
    },2000)
}

private fun doSomething() {
    Toast.makeText(this,"Hi! I am Toast Message",Toast.LENGTH_SHORT).show()
}
}

使用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();

我喜欢干净的东西: 下面是我的实现,在方法中使用的内联代码

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