“This is the 18th day of my participation in the August Gwen Challenge.
The Handler mechanism involves five classes
- Handler (for processing messages)
- Message (Message object)
- MessageQueue (store message objects in order)
- Looper (internal loop, constantly fetching messages from MessageQueue)
- HandlerThead
First let’s look at a diagram of the Handler message mechanism
A little confused?
Let’s start with the source code, starting with handler.java
Conclusion:
-
Handler uses the MessageQueue object and calls its enquequeMessage method to stuff messages to MessageQueue
-
MSG. Target is the object of the handler itself
So what is enquequeMessage?
Conclusion:
- EnquequeMessage was to sort incoming messages by delay time, with 0 milliseconds first and non-0 milliseconds last
Let’s move on to Lopper.java
Come to the conclusion
- The loop method is actually an infinite loop inside
- Fetch messages from the message queue via queque.next(), block if there are no messages, and execute down if there are
- If there is a message, the dispatchMessage method is used to distribute the message. Note that the dispatchMessage method belongs to the Handler object
Go to message.java
Conclusion:
- Finally, handleMessage is called for the user to process
- The target variable is the main reason why the system creates multiple handlers to handle hundreds or thousands of messages. It binds each message to a Handler and assigns that Handler to handle the message
- The process from sendMessage to handleMessage looks like this
So here’s the question:
- The loop is an infinite loop inside the UI thread. If the loop is in the UI thread, the thread will block.
Android definitely doesn’t allow this to happen. To fix this, HandlerThread comes in and starts a separate child thread for the handler
HandlerThread inherits Thread from Thread into handlerThread.java and we’ll start with the key method run
Conclusion:
- Perpare () is primarily used to initialize the creation of a Looper object and store the object in a thread variable for use by thread objects
- Call the loop method after initialization to start an infinite loop
- If you use looper yourself, you need to start a thread, otherwise the UI thread will be blocked and the perpare and loop methods will be called
- Normally we do not need to start the thread when using the handler because the system has already started the ActivityThread thread for us
Handler Message distribution process
additional
ActivityThread also has a loop method
In fact, Android applications are launched and run by handlers, which continuously process system messages so that all four components work properly