Executing operations on UI thread after delay

2k Views Asked by At

I want to implement some operations on UI thread after a delay of a few seconds and have tried this approach -

final Handler handler1 = new Handler();
final Runnable r = new Runnable() {
public void run() {
// operations to do 
 }
};
runOnUiThread(new Runnable() {
 @Override
 public void run() {
 handler1.postDelayed(r, 1000);
 }
 });

Here I have two runnable objects, so my question is that are the operations I'm performing here being executed in UI thread or another thread because I don't directly execute the operations in Runnable object of the UI thread. Also if this is not the right approach to execute operations in UI thread after a delay, please suggest any modifications required.

1

There are 1 best solutions below

1
On

When you post a Runnable with a Handler, the Handler executes it on whatever Thread created that Handler.

Handler's default constructor new Handler() is a synonym of new Handler(Looper.myLooper()). That might mean that the Handler will execute Runnables on the main thread, but only if the instantiation happened on the main Thread.

Either way, what you're doing is redundant. The runOnUiThread() is useless. Just change the Handler's constructor:

final Handler handler1 = new Handler(Looper.getMainLooper());
handler1.postDelayed(r, 1000);