First, the principle
1. Message
Message, understood as a data unit for communication between threads. For example, when a background thread needs to update the UI after processing the data, it can send a message to the UI thread that contains the updated information.
2. Message Queue
Message queues, which are used to store messages posted via handler, in advance of first out execution.
3. Handler
Handler is the primary processor of the message, which is responsible for adding messages to the queue and processing messages in message queues.
4. Looper
The loop, playing the role of the bridge between message queue and handler, loops through and gives the corresponding handler for processing. The normal thread is also converted to a looper thread (the Looper thread is actually a looping thread).
Code:
The code is as follows |
Copy Code |
public class Looperthread extends Thread {public
Handler Mhandler;
@Override public
Void Run () {
//Initialize the current thread to Looper thread
looper.prepare ();
// ... Other processing, such as instantiating Handler
Mhandler = new Handler () {public
void Handlemessage (msg) {
//process incoming M Essages here
}
;
Start the loop processing of Message Queuing
looper.loop ();
}
|
As shown in figure:
5. Thread
UI thread is usually the main thread, and the Android launcher creates a message Queue for it.
Each thread can contain a Looper object and a MessageQueue data structure. In your application
In order, you can define subcategories of handler to receive messages sent by Looper.
To sum up, the relationship between the message Queue, Handler, and looper them is as follows: