Do you want to learn the uses of Android Handler ? Here in this post I have explained everything you need to know about Handler in general.
We will look at each of the topics one by one. Meanwhile, you can quickly navigate to certain portion using quick links below.
Quick Navigation
What is Handler in Android ?
Before we get started. Let us understand Handler in Android.
What really is a Handler ?
A Handler in android is a class
in package android.os
. And, it helps us with the execution of task at a specified thread. Not only that, we can even use handler to schedule task execution at specified time in future.
So, Handler helps in queuing the task for us on specified thread. If we want to do something on a specific thread. We can specify the Looper and handler will add the task in the message queue.
One thing you might get confused about is Looper and Message Queue. They are actually the same thing. Calling Looper.prepare()
in a Thread
will create a message queue for that thread.
See the image below to get a clearer insight on Handler and message queue.
Handler in Android Example
Here is a simple code snippet for Java. This will give you an idea of the usage.
We will just print something on logcat after 5 seconds.
Log.d("MCHLoop", "called test method.");
Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
@Override
public void run() {
Log.d("MCHLoop", "after 5 seconds.");
}
};
handler.postDelayed(runnable, 5_000L);
Log.d("MCHLoop", "added runnable to message queue.");
Code language: Java (java)
If you add the above code to your Activity/ Fragment and run the app. You will see the following output after 5 seconds.
You can do anything in the run method after 5 seconds. But remember we are still on the main thread because Looper.getMainLooper()
gets the message queue for the main thread.
Did you notice the highlighted line Looper.getMainLooper()
? This defines where the code runs. And it’s always the main thread, so whenever you call the static method the message queue for main thread is returned.
Handler Constructor is Deprecated
Before we move on let us quickly look at the deprecation of the Handler
‘s default constructor.
Recently we have seen the default empty constructor has been deprecated. Let us understand why it was deprecated and what can we do about the deprecation.
The default constructor Handler() doesn’t really specify a looper. Instead it internally gets the looper for current Thread. Which can cause problems in situations.
So to solve the this problem a new constructor has been put in place. It takes in a looper instance, which must be explicitly passed in by the developer.
You can see the example above. As we have passed Looper.getMainLooper()
. You could instead use
Handler handler = new Handler(Looper.myLooper());
Code language: Java (java)
But you should really look into HandlerThread instead of directly creating a looper using Looper.myLooper()
for any thread.
Main Thread vs Background Thread
By now you might have understood what the handler is. But here is something you must understand too.
Everything on android is done on MainThread. And by everything I mean the UI and other code you execute. They are executed on the Main Thread. This might not make sense to you if you are just starting with Android development.
Let us look at to kinds of Thread briefly.
Main Thread: Everything you code will execute on the main thread. This includes all the UI operations and normal logic. Everything you code is run on main thread unless you explicitly specify any other thread.
Background Thread: You should execute all your long operations on background Thread. It will make sure that the UI will not get stuck while doing long running operations. If the UI Thread gets stuck for more than 5 seconds. You will receive a ANR (App Not Responding) which then leads to a crash.
The example I provided earlier is run on MainThread. But you will get an error when you try to do network operations or long tasks on MainThread.
Look into HandlerThread implementation. It will help you understand how you should use it.
Why is Handler used in Android ?
I have explained about the Thread in above sections. Now if you are still confused about why is it used. I will explain it in simple terms below.
You need handler to handle the message passing between threads. And by message passing I mean communication between multiple threads.
For instance
If we try to update the value of a view from Worker ( Background ) Thread. We will receive an exception and your application will crash.
Sure, you can use the runOnUiThread()
to solve the problem. But how the method works is our main concern here.
What the runOnUiThread()
does under the hood is post message to the UI Thread’s Message Queue. In other word use the Looper.getMainLooper()
.
And the code will look something like below. See the example code:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
void run() {
// you view update code here
}
});
Code language: Java (java)
You see that’s basically everything that is done by the runOnUiThread()
method for us.
Now you see why the Handler class is used. Try to zone out a bit and see how the code executes on main thread once Looper.getMainLooper()
is used.
The sections above makes sense now, don’t they ?
Exploring the Handler API in Android
Now, le tus look at most of the common APIs we will be using on our everyday job as android developer.
Handler.post()
We use this method to submit our task to the Message Queue. Our task will be executed by the system in sometime in the next cycle.
It means almost immediately for the system and immediately for humans. You should use this most of the time.
Example:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
// I will be executed almost immediately
}
});
Code language: JavaScript (javascript)
Handler.postDelayed()
If you want to execute some task after X amount of time you should use it. Let us see an example of executing task after 10 seconds.
You might recall this from the first example above.
Example:
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
// I will be executed after 10 seconds
}
}, TimeUnit.SECONDS.toMillis(10));
Code language: Java (java)
This was a simple explanation about the Handler to get you started. You can find other articles aout the same topic that might help you.
Keep learning, Keep programming.
Recommended
Android Get Screen Width & Density in Pixels
ShapableImageView in Android: Make Circular Image Border
Using Android Handler Thread in Android for Multi-threading