Principle analysis and example code of Android handler
Principle analysis of Android handler
Handler is a headache for countless Android developers. I hope my article here today can completely eradicate this problem for you
Today, I'll analyze the principle of handler in detail
Reason for using handler
1. Updating UI by multithreading will lead to UI interface disorder. 2. Locking will lead to performance degradation. 3. Only update UI in the main thread and poll for processing
Introduction to handler
In fact, the key method is two sendmessages, which are used to receive messages
The other is handlemessage, which is used to process the received message
The following is a demo of the communication between the sub thread and the main thread, which I wrote with reference to the crazy Android handout
Some modifications have been made to the original demo
Hanler and looper, principle analysis of messagequeue
1. Handler sends messages to process messages (usually sends messages to itself), because handler can be used in different threads
2. Looper management messagequeue
Loop.loop is an endless loop, constantly fetching messages from the messagequeue. If there is a message, it will process the message, and if there is no message, it will be blocked
This is the source code of looper.loop. In essence, it is an endless loop that constantly reads its own messqueue messages
3. The messqueue is a message queue. The messages sent by the handler will be added to the messqueue of the looper inline with the handler and managed by the looper
This is the looper constructor, which does two jobs,
1. Generate a message associated with yourself
2. Bind to current thread
The main thread has generated a looper during initialization,
If other threads want to use handler, they need to generate a looper bound by their own thread through looper. Prepare()
This is the looper. Prepare () source code. In essence, the constructor is used to generate a looper
4. When the handler sends a message, it will save the message in the messagequeue of its associated looper. How does it find this messagequeue
This is the constructor of handler. It will find a looper associated with itself
Yes, they are also associated through threads. After obtaining looper, you can naturally obtain its messagequeue
5. Let's look at how the handler calls back the handlermessage after sending a message
This is the final source code for the handler to send messages. It can be seen that a message is added to the messagequeue. Why can the handler call back the handlemessage method in time after sending a message
Please look at the loop method above. There is a sentence MSG. Target. Dispatchmessage (MSG) in the for loop;
This is the sentence. See, it will call hanlermessage, and everything is connected
Thank you for reading, hope to help you, thank you for your support to this site!