How to call a method after a delay with handler

How to call a method after a delay with handler

Hi, sometimes we need to execute my method or we can say my function after a time delay. In that situation what can I do? So the answer is - Use Handler() for that. A Handler is a utility class that facilitates interacting with a Looper.

Handlers, on the other hand, are background threads that allow you to communicate with the UI thread.

It's so simple, you can create an Object of Handler() method or you can use directly. Let's see both portions.

First Option:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //your task
                }
}, 200);

Second Option:

new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //your task
                }
            }, 200);

Both handlers are same, and both will execute your code after 200 milliseconds.

Related posts

Write a comment