Understanding Android Core: Looper, Handler, and HandlerThread
This Article covers Android Looper, Handler, and HandlerThread. These are among the building blocks of Android OS.
In my own experience, I have used them in a very limited context until recently. My use case involved sending tasks to the main/ui thread, primarily to update the UI from any other thread. The other aspects of the multi-threaded operation were handled through alternate ways like ThreadPoolExecutor, IntentService, and AsyncTask.
MultiThreading and task running are old subjects. Java itself has java.util.concurrent package and Fork/Join framework to facilitate it. Several libraries have been written to streamline asynchronous operations. RxJava is the most popular library today for reactive programming and designing an asynchronous application.
So, why am I writing about the old school?
Looper
, Handler
, and HandlerThread
are the Android’s way of solving the problems of asynchronous programming. They are not old school, but a neat structure on which a complex android framework is built.
For new developers, it’s highly recommended to understand the principles behind them and experienced one’s should revisit this topic to recollect the minor details.
I have also created a video tutorial for this subject, and I highly recommend to watch it. Click here to watch now.
Use Cases:
- The main thread in Android is built with a
Looper
andHandlers
. So, the understanding of it is essential to create an unblocked responsive UI. - The developers writing libraries cannot afford to use third party libraries because of the library size. So, for them, the best option is to utilize the existing available resource. Writing own solution for it may not always get that level of efficiency and optimization.
- The same argument can also be made for companies/individuals shipping out SDKs. The clients can have varied implementations, but all of them will share the common android framework APIs.
- Understanding them fully will enhance the capacity to follow the Android SDK and package classes in general.
30% DISCOUNT NOW
Android Online Course for Professionals by MindOrks
Join and learn Dagger, Kotlin, RxJava, MVVM, Architecture Components, Coroutines, Unit Testing and much more.
Let’s start the exploration/revision with a questionnaire.
I expect the reader to have the basic understanding of java threads. If you need, then get a quick overview of java Thread and Runnable.
What is the problem with java thread?
Java threads are one-time use only and die after executing its run method.
Can we improve upon it?
The Thread is a double edged sword. We can speed up the execution by distributing the tasks among threads of execution, but can also slow it down when threads are in excess. Thread creation in itself is an overhead. So, the best option is to have an optimum number of threads and reuse them for tasks execution.
Model for thread reusability:
- The thread is kept alive, in a loop via it’s
run()
method. - The task is executed serially by that thread and is maintained in a queue (MessageQueue).
- The thread must be terminated when done.
What is the Android’s way of doing it?
The above model is implemented in the Android via Looper
, Handler
, and HandlerThread
. The System can be visualized to be a vehicle as in the article’s cover.
MessageQueue
is a queue that has tasks called messages which should be processed.Handler
enqueues task in theMessageQueue
usingLooper
and also executes them when the task comes out of theMessageQueue
.Looper
is a worker that keeps a thread alive, loops throughMessageQueue
and sends messages to the correspondinghandler
to process.- Finally
Thread
gets terminated by calling Looper’squit()
method.
One thread can have only one unique Looper and can have many unique Handlers associated with it.
Creating Looper and MessageQueue for a Thread:
A thread gets a Looper
and MessageQueue
by calling Looper.prepare()
after its running. Looper.prepare()
identifies the calling thread, creates a Looper
and MessageQueue
object and associate the thread
with them in ThreadLocal
storage class. Looper.loop()
must be called to start the associated looper. Similarly, the looper
must be terminated explicitly through looper.quit()
.
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
// this will run in non-ui/background thread
}
};
Looper.loop();
}
}
Creating Handler for a Thread:
A Handler
gets implicitly associated with the thread that instantiates it via thread’s Looper
, but we can explicitly tie it to a thread by passing the thread’s looper
in the constructor of the Handler
.
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// process incoming messages here
// this will run in the thread, which instantiates it
}
};
Sending messages to the MessageQueue
via Handler
can be done by two modes:
Message
: It is a class that defines various useful methods to deal with message data. To send an object we set the obj variable.
Message msg = new Message();
msg.obj = "Ali send message";
handler.sendMessage(msg);
Detailed overview of Message
class can be found here:https://developer.android.com/reference/android/os/Message.html
2. Runnable
: A runnable can also be posted in the MessageQueue
. Ex: posting and running a task in the main thread.
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// this will run in the main thread
}
});
In the above example, we create a Handler
and provide Looper
associated with the main thread. This associate this handler to the main thread. When we post the Runnable
, it gets queued in the main thread’s MessageQueue
and then executed in the main thread.
Handler is capable of message manipulation in a wide variety of ways, which can found here: https://developer.android.com/reference/android/os/Handler.html
Creating an own thread and providing Lopper
and MessageQueue
is not the right way to deal with the problem. So, Android has provided HandlerThread
(subclass of Thread
) to streamline the process. Internally it does the same things that we have done but in a robust way. So, always use HandlerThread
.
One of the ways to create the HandlerThread is to subclass it and most of the time you will be using this method.
private class MyHandlerThread extends HandlerThread {
Handler handler;
public MyHandlerThread(String name) {
super(name);
}
@Override
protected void onLooperPrepared() {
handler = new Handler(getLooper()) {
@Override
public void handleMessage(Message msg) {
// process incoming messages here
// this will run in non-ui/background thread
}
};
}
}
Note: We have instantiated the Handler when the onLooperPrepared()
is called. So, that Handler
can be associated with that Looper
.
Looper
is only prepared after HandlerThread’sstart()
is called i.e. after the thread is running.- A
Handler
can be associated with aHandlerThread
, only after it’sLooper
is prepared.
Other way to create the HandlerThread:
HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
Note: HandlerThread needs to call myHandlerThread.quit()
to free the resources and stop the execution of the thread.
I would suggest practicing the above codes, so you can grasp their little details.
I have created an example project for Post Office simulation. Post Office is built upon HandlerThread and Clients communicate with the help of the Post Office. A Simulator class creates few Client Bots and delegate their communication to the MainActivity, which renders it in a live feed.
I have also created a video tutorial for this subject, and I highly recommend to watch it. Click here to watch now.
No comments:
Post a Comment