Why to Use Handlers While Runonuithread Does The Same

Why to use Handlers while runOnUiThread does the same?

Activity.runOnUiThread() is a special case of more generic Handlers. With Handler you can create your own event query within your own thread. Using Handlers instantiated with the default constructor doesn't mean "code will run on UI thread" in general. By default, handlers are bound to the Thread from which they were instantiated from.

To create a Handler that is guaranteed to bind to the UI (main) thread, you should create a Handler object bound to Main Looper like this:

Handler mHandler = new Handler(Looper.getMainLooper());

Moreover, if you check the implementation of the runOnUiThread() method, it is using Handler to do the things:

  public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}

As you can see from code snippet above, Runnable action will be executed immediately if runOnUiThread() is called from the UI thread. Otherwise, it will post it to the Handler, which will be executed at some point later.

What is the difference between Handler vs runOnUiThread?

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

What is the difference between runOnUiThread method and Handler? Which one is the best to use?

Both are actually same. Both runOnUiThread and Handler#post runs the passed Runnable in the UI Thread.

FYI, you can also execute any Runnable on UI Thread with the help of any View by calling the method View#post(runnable).

Since all approaches uses Handler internally, all are same and there won't be any difference in using any of these.

What is the difference between these methods for running code on UI Thread?

In Android, a Thread might have one Looper or MessageQueue. Handler is used to send Message or post Runnable to MessageQueue of a Thread, and it must always be associated with a Looper or a MessageQueue of a Thread.

Method 1

new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// Code here will run in UI thread
}
});

When open an app, Android create a new thread (called main thread or UI thread) with a Looper and MessageQueue, this thread is used to render UI and process input events from users.

The above code is create a Handler and associated with Looper of UI thread, so the runnable will be queued to MessageQueue of UI thread, and will be executed later.

Method 2

new Handler().post(new Runnable() {
@Override
public void run() {
// Code here will run in UI thread
}
});

Creating a Handler and associated with Looper of current thread, there are 3 cases:

  • If this code is executed on UI thread, then the runnable will be queued to MessageQueue of UI thread and will be executed later.
  • If this code is executed on a background thread, if this thread has a Looper, then the runnable will be queued to MessageQueue of background thread and will be executed later.
  • If this code is executed on a background thread and this thread has no Looper, then an exception will be thrown.

Method 3

runOnUiThread(new Runnable() {
@Override
public void run() {
// Code here will run in UI thread
}
});

runOnUiThread is just a utility method of Activity, it used when you want to execute some code on UI thread. The logic behind this method is if current thread is UI thread, then execute it immediately, otherwise used Handler to post a message to MessageQueue of UI thread (like method 1).

What's the difference between Activity.runOnUiThread(runnable action) and Handler.post()?

Activity.runOnUiThread, like it's name implies, will execute the Runnable in the thread that is currently responsible for the UI. So, if you have a CPU intensive task, it can make the UI unresponsive for a short period of time. Conversely, Handler provides a way for you to create a thread, run some code, and notify the UI when you are done (i.e Handler.sendMessage).

The docs for Handler state this better than I can:

When a process is created for your
application, its main thread is
dedicated to running a message queue
that takes care of managing the
top-level application objects
(activities, broadcast receivers, etc)
and any windows they create. You can
create your own threads, and
communicate back with the main
application thread through a Handler.
This is done by calling the same post
or sendMessage methods as before, but
from your new thread. The given
Runnable or Message will than be
scheduled in the Handler's message
queue and processed when appropriate.

How runOnUiThread is working in the following code without effecting the existing UI Thread

There are two types of thread in Android.

1 is UI or Main thread on which your UI elements (layouts) are rendered.

2 is Worker Thread in which long task should be executed (like AsyncTask & Networking).

If you write some task in new Thread, that mean that task will be executed in worker thread.

Now you will use runOnUiThread or new Handler(Looper.getMainLooper()) because you can not touch UI elements in worker thread.

So basically when you are updating UI like setText(), or Toast or any UI operations, you will have to UI thread and you should use worker thread when you are doing some long executions.

Edit

Generally we don't have to manage threading in Android. Because all libraries we use are smart. Although in some cases we have to manage threading as well.

Example

Assume you are calling an web-service(api) in a new Thread, now when response comes you want show a Toast. If you just write Toast.show... directly in response inside worker Thread you will get exception.

Only the original thread that created a view hierarchy can touch its views.

Now to overcome this issue you have to use runOnUiThread, so that you can show Toast.

Difference between android runOnUiThread and simple code in java

Assuming that you meant simple code for UIThread code,

What is a thread ?

A thread defines a process running

First runOnUiThread ..

Runs the specified action on the UI thread. If the current thread is
the UI thread, then the action is executed immediately
. If the current
thread is not the UI thread, the action is posted to the event queue
of the UI thread.

What is UIThread

  • Main thread of execution for your application
  • Most of your application code will run here onCreate, onPause, onDestroy, onClick, etc.

    So simply Anything that causes the UI to be updated or changed HAS to happen on the UI thread

When you explicitly spawn a new thread to do work in the background, this code is not run on the UIThread.Now what if you want to do something that changes the UI?
Then you are welcome to runOnUiThread

You have to use runOnUiThread() when you want to update your UI from a Non-UI Thread. For eg- If you want to update your UI from a background Thread. You can also use Handler for the same thing.



Related Topics



Leave a reply



Submit