The message mechanism of Android is mainly refers to the operation mechanism of handler, handler operation needs the bottom MessageQueue and looper support;
MessageQueue: Message Queuing, whose memory stores a set of messages that provide insertions and deletions in the form of a queue, internal structure: using
A single-linked list of data structures to store message queues;
Looper: Processing MessageQueue message, will be in an infinite loop to find out whether there is a new message, have to deal with the non-wait, but also to use a special concept-threadlocal: Not a thread, function: You can store data in each thread,
Threadlocal can store and provide data in different threads with no interference, and the looper of each thread can be easily obtained through threadlocal. The thread defaults to no looper, and if you need to use handler, you must create looper for the thread;
The UI thread, Activitythread,activitythread, is created to initialize the Looper, which is why the handler can be used by default in the main thread.
Once the handler is created, Looper and MessageQueue, Handler can work together, 1. Send a handler to the runnable from within by Handler post method to take processing
2. Sending a message via the handler send method, which is also handled in Looper, where the Post method is finally completed by the Send method;
Send procedure: When the handler send method is called, it calls MessageQueue's Enqueuemessage method to put the message into the message queue, and then Looper discovers a new arrival, the message is processed.
The Handlemessage method of runnable or handler in the final message is called. Note that Looper is running in the same thread as the creation of the handler, so the business logic in handler is switched to the one where the handler is created
Thread to execute it.
Android Messaging Mechanism Learning notes