Understanding Looper
Before we can understand Handler
, we need to meet the aptly named Looper
. Looper
is a simple class that quite literally loops forever, waiting for Messages to be added to its queue and dispatching them to target Handlers. It is an implementation of a common UI programming concept known an Event Loop.
To set up a Looper
thread, we need to invoke two static methods of Looper
—prepare
and loop
—from within the thread that will handle the message loop.
class SimpleLooper extends Thread { public void run() { Looper.prepare(); Looper.loop(); } }
That was easy; however, the SimpleLooper
class defined here provides no way to add messages to its queue, which is where Handler
comes in.
Handler
serves two purposes—to provide an interface to submit Messages to its Looper
queue and to implement the callback for processing those Messages when they are dispatched by the Looper.
To attach a Handler to SimpleLooper
, we need to instantiate the Handler
from within the...