-4

I come across both runOnUiThread and Handlers, but to me its still seems to be a doubt as on which facts do they differ exactly.

What would be the best way to update UI? Should I use runOnUiThread or Handler?

Already gone through link. Still not able to justify the difference.

Thank you in Advance

Community
  • 1
  • 1

3 Answers3

3

runOnUiThread is a method that uses main ui handler so basically they are the same. The only difference is that if you call it inside the ui handler, you just run it instead of post it.

public final void runOnUiThread(Runnable action) {
   if (Thread.currentThread() != mUiThread) {
      mHandler.post(action);
   } else {
      action.run();
   }
}
Barışcan Kayaoğlu
  • 1,294
  • 3
  • 14
  • 35
1

Handlers are a nice way to implement an event queue. It doesn't have to run on the main thread, you can set your own looper. RunOnUiThread is basically a shortcut so you dont actually have the initiate a handler and so on.

breakline
  • 5,776
  • 8
  • 45
  • 84
  • I known this other then that if you know please answer. – Nikunj Patel Sep 07 '16 at 10:29
  • What do you mean "other than that"? If you need to use a Handler you will need to allocate a memory for each of your handler and you need to control if you already are working in your ui handler. The method itself does that for you. – Barışcan Kayaoğlu Sep 07 '16 at 10:33
1

Handler register itself in which it is declared. or you can set the looper manually also.

Handler is particular useful if you have want to post multiple times data to the main thread.

runOnUiThread is method of Activity. so when you need to update the UI Thread, you must write the code in the following way.

       runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // update the ui

                }
            });

So there is no re-usability.

for example you want to update the status of the file downloading. you should write the above method multiple times.

But using Handler objects update the UI multiple times using same Handler Object.

Kona Suresh
  • 1,836
  • 1
  • 15
  • 25