-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

0

3 Answers 3

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();
   }
}
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.

2
  • I known this other then that if you know please answer. Sep 7, 2016 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. Sep 7, 2016 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.