Looper/Handler API - Part 202 Feb 2017 Android #android #handlers
This is part two of looper/handler API series
- Looper/Handler API - Part 1
- Looper/Handler API - Part 2
- Looper/Handler API - Part 3
- Looper/Handler API - Part 4
In previous article, we have learnt about why we need handler API, classes used in this API and their responsibilities and in the last we have written a small app for demonstration. In this article, I will explain the example code.
We started off by writing a worker thread. Let’s see what’s in
Worker Thread's source code and how it works.
Ok. I will explain each and every thing at very basic level here.
We extend our
java.lang.Thread class because it’s a thread and implement
Handler.Callback which is the callback
Looper will dispatch messages through this callback).
Handler is declared as a private field. It is the interface used by
Main Thread to add
Message in the
run method, we call
Looper.prepare() to attach a
Looper with current thread (WorkerThread). After calling this method, our thread
has a looper attached to it, we can initialize (
mHandler = new Handler(this)). The default constructor of
Handler binds the handler
Looper of current thread. Note that we have also passed
this to constructor, it is for
Handler.Callback. By contract
enforces us to override
handleMessage(Message msg). All the messages passed to
Looper's queue will be dispatched to
through this method.
Once we have set up
Handler, we can start the loop and wait for message.
Looper.loop() will block the current thread
and whenever a message is sent to the
MessageQueue it will be dispatched to the
handleMessage(Message msg) method of
Now let’s go to
MainActivity ans see what’s happening there!
MainActivity we start off by initializing the worker Thread. Next we override
onStop method, here we are quiting the loop so that
onDoWork methods is registered as
onClick listener for Button in
layout. Whenever this method is called, we get the handler from
and insert a
Message in queue using
sendMessage adds the method in the queue which is eventually dispatched to
handleMessage(Message msg) in
In upcoming articles, I will write in detail about messages and other callbacks related to handler. Read part 3 here