Skip to content

How to call a method after a delay in Android

To call a method after a delay in Android, you can use the Handler class and the postDelayed() method. The postDelayed() method takes a Runnable and a delay in milliseconds as arguments, and it runs the Runnable after the specified delay. By default, postDelayed() posts tasks to the main thread, so it is best suited for UI updates or main-thread operations.

Here's an example of how you can use the Handler class to call a method after a delay in Android:


java
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

public class MainActivity extends Activity {
  private static final int DELAY = 5000; // 5 seconds
  private Handler handler;
  private Runnable runnable;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Create a new Handler attached to the main thread
    handler = new Handler(Looper.getMainLooper());

    // Create a Runnable that calls the doSomething() method
    runnable = new Runnable() {
      @Override
      public void run() {
        doSomething();
      }
    };

    // Post the Runnable with a delay
    handler.postDelayed(runnable, DELAY);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    // Remove callbacks to prevent memory leaks if the activity closes before the delay
    if (handler != null && runnable != null) {
      handler.removeCallbacks(runnable);
    }
  }

  private void doSomething() {
    // Do something here after the delay
  }
}

In this example, a Handler is created and a Runnable is created that calls the doSomething() method. The Runnable is then posted to the Handler with a delay of 5 seconds using the postDelayed() method. The doSomething() method will be called after the delay. For modern Android development, consider using Kotlin Coroutines (delay/launch) or View.postDelayed() as safer, lifecycle-aware alternatives.

I hope this helps! Let me know if you have any questions.

Dual-run preview — compare with live Symfony routes.