foreword
In the
Android
development of multi-threaded application scenarios , theHandler
mechanism is very commonToday, I will explain in detail how the
Handler
mechanism works, I hope you will like it
content
1. Definitions
A set of Android
message passing mechanisms
2. Function
In a multi-threaded application scenario, the operation information that needs to be updated in the worker thread is UI
passed to the UI
main thread , so as to realize UI
the update processing of the pair of worker threads, and finally realize the processing of asynchronous messages.
3. Why use the Handler
message passing mechanism
- Answer: Multiple threads update the UI concurrently while ensuring thread safety
- The specific description is as follows
4. Related concepts
Handler
The related concepts in the mechanism are as follows:
In the following explanation, I will directly use the English name to explain, namely
Handler
,Message
,Message Queue
,Looper
, I hope you are familiar with the relevant concepts first
5. Analysis of the working principle
Below, I will qualitatively explain Handler
the workflow of the mechanism
5.1 Workflow Analysis
Handler
The workflow of the mechanism mainly includes 4 steps:
1. Asynchronous communication preparation
2. Message sending
3. Message loop
4. Message processing
The details are as follows:
5.2 Workflow diagram
5.3 Schematic
5.4 Special attention
The correspondence between threads (Thread)
, loopers, (Looper)
and handlers is as follows:(Handler)
- 1 thread
(Thread)
can only bind 1 looper(Looper)
, but can have multiple handlers(Handler)
- 1 looper
(Looper)
can bind multiple handlers(Handler)
- 1 handler can
(Handler)
only bind 1 1 circulator(Looper)
So far, Handler
the working principle of the asynchronous message passing mechanism has been explained.
6. Summary
- This article
Handler
provides a comprehensive explanation of how the mechanism works - Next, I will continue to explain
Android
in theHandler
relevant knowledge of the asynchronous communication transfer mechanism in