What is Looper?
FROM DOCS
Looper
Class used to run a message loop for a thread
. Threads by default do not have a message loop associated with them; to create one, call prepare()
in the thread that is to run the loop, and then loop()
to have it process messages until the loop is stopped.
Looper
is a message handling loop:MessageQueue
, which contains a list messages. An important character of Looper is that it's associated with the thread within which the Looper is created.Looper
is named so because it implements the loop – takes the next task, executes it, then takes the next one and so on. The Handler
is called a handler because someone could not invent a better nameLooper
is a Java class within the Android user interface that together with the Handler class to process UI events such as button clicks, screen redraws and orientation switches.How it works?
Creating Looper
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
SAMPLE CODE
class MyLooperThread extends Thread {
public Handler mHandler;
public void run() {
// preparing a looper on current thread
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
// this will run in non-ui/background thread
}
};
Looper.loop();
}
}
For more information check below post