Threads Running on UI Thread
Development of Android Application
Competitive Exams Techprep
UI Thread –
Every android application wll have a main thread for the execution of
your application, this thread is called Main Thread or UI Thread .
Your application Components like Activities, Services,
ContentProviders are all created in this thread, and any system calls to
those components are performed in this thread.
If your application only has a single activity, then all of the lifecycle
methods and most of your event handling code is run in this UI Thread
and also this is where all of the updates to the UI are made.
Working of UI Thread
UI thread is responsible for showing components in UI, lifecycle
methods of the mainActivity and updates to UI, but it doesn’t terminate
after it handles one of the operations, it uses
a MessageQueue , Looper, Handler and HandlerThread for handling
these operations.
Message Queue: The UI thread has a message queue which it has to
execute. If the message queue is empty, the UI thread is blocked but is
waiting to respond to any changes in the message queue.
This message queue consists of pieces of work, one after the another.
That is done using a Looper.
Handler: They enqueue the task in the Message Queue using Looper
and also executes them when the task comes out of the Message queue.
There are two main uses for a Handler:
(1) to schedule messages and runnables to be executed at some
point in the future.
(2) to enqueue an action to be performed on a different thread
than your own.
Handler only works for a thread that has a looper and a message queue.
You can create your own threads, and communicate back with the UI
thread through a Handler.
Looper:This is the class used to run a message loop for a thread. A
thread gets a Looper and MessageQueue by calling prepare() method
after its running. prepare() identifies the calling thread, creates a
Looper and MessageQueue object and associate the thread with them
in storage class. loop() method must be called to start the associated
looper.
HandlerThread: This is a class that extends the Thread class. So
basically this is a Thread that has a Looper, and the Looper can then be
used to create Handlers.
start() method must be called to run this HandlerThread and only after
calling this method will a Looper be prepared and a Handler will be
associated with this Thread. HandlerThread needs to call quit() to free
the resources and stop the execution of the thread.