Android Asynchronous Communication: Graphical and Text Detailed Explanation of the Working Principle of the Handler Mechanism

foreword

  • In the Androiddevelopment of multi-threaded application scenarios , the Handlermechanism is very common

  • Today, I will explain in detail how the Handlermechanism works, I hope you will like it


content

Schematic


1. Definitions

A set of Androidmessage passing mechanisms


2. Function

In a multi-threaded application scenario, the operation information that needs to be updated in the worker thread is UIpassed to the UImain thread , so as to realize UIthe update processing of the pair of worker threads, and finally realize the processing of asynchronous messages.
Schematic


3. Why use the Handlermessage passing mechanism

  • Answer: Multiple threads update the UI concurrently while ensuring thread safety
  • The specific description is as follows

Schematic


4. Related concepts

HandlerThe 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

Schematic


5. Analysis of the working principle

Below, I will qualitatively explain Handlerthe workflow of the mechanism

5.1 Workflow Analysis

HandlerThe 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:

Schematic

5.2 Workflow diagram

Schematic

5.3 Schematic

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)

Schematic

So far, Handlerthe working principle of the asynchronous message passing mechanism has been explained.


6. Summary

  • This article Handlerprovides a comprehensive explanation of how the mechanism works
  • Next, I will continue to explain Androidin theHandler relevant knowledge of the asynchronous communication transfer mechanism in

Please give a thumbs up/comment! Because your encouragement is the biggest motivation for my writing!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325345801&siteId=291194637