Handler message under Android
The implementation principle of handler message in Android is studied:
When new handler(), get the data under the current thread from ThreadLocal
The reference of messagequeue under the looper instance is saved in the handler In the mqueue attribute
The essence of a handler sending a message is to write a value to this collection
Several important nodes
1.Looper. Perpare() instantiates the looper object of the current thread
2. New handler() selects the looper object of the current thread
3.handler. Sendmessage() essentially sends a message by writing a value to the mqueue and storing a message to the selected looper
4.Looper. The loop () method retrieves the message of the loop object of the current thread and performs related operations. In essence, it takes the value from the current messagequeue
So you should pay attention when using
1. New handler and looper loop,Looper. Prepare is the same thread, and SendMessage can be sent on any thread
2. The new handler must be in looper After perpare() (if looper does not exist, there must be no mqueue)
3. By default, the main thread calls looper loop,Looper. Prepare other threads need to be handled manually