How to call a method after a delay in Android


Question

I want to be able to call the following method after a specified delay. In objective c there was something like:

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

Is there an equivalent of this method in android with java? For example I need to be able to call a method after 5 seconds.

public void DoSomething()
{
     //do something here
}
1
693
9/4/2014 7:31:52 AM

Accepted Answer

Kotlin

Handler().postDelayed({
  //Do something after 100ms
}, 100)


Java

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


1698
3/14/2019 10:50:08 AM

I couldn't use any of the other answers in my case. I used the native java Timer instead.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon