preface

  • In Android multi-threaded application scenarios, the Handler mechanism is very common

  • Today, I’ll explain how the Handler mechanism works in graphic detail. I hope you’ll enjoy it


directory


Definition 1.

An Android messaging mechanism


2. The role

In the multi-threaded application scenario, the operation information of UI updating in the worker thread is transferred to the UI main thread, so as to realize UI updating processing by the worker thread and finally realize asynchronous message processing


3. WhyHandlerMessaging mechanism

  • A: Multiple threads update the UI concurrently while keeping it thread-safe
  • Detailed description is as follows


4. Related concepts

The concepts related to the Handler mechanism are as follows:

I’ll use the names Handler, Message, Message Queue, and Looper to familiarize you with the concepts


5. Working principle analysis

Next, I’ll take a qualitative look at how the Handler mechanism works

5.1 Workflow analysis

The workflow of the Handler mechanism consists of four steps:

  1. Preparation for Asynchronous Communication
  2. Message is sent
  3. Message loop
  4. Message processing

The details are as follows:

5.2 Workflow Flow Chart

5.3 sketch

5.4 Special Attention

The mapping between threads, Looper and Handler is as follows:

  • A thread(Thread)Only one circulator can be bound(which), but there can be multiple processors(Handler)
  • 1 circulator(which)Multiple handlers can be bound(Handler)
  • One handler(Handler)Only one circulator can be bound(which)

This concludes how the asynchronous messaging mechanism of the Handler works.


6. Summary

  • In this paper,HandlerThe working principle of the mechanism is fully explained
  • In the next article, I’ll go furtherHandlerAsynchronous communication transmission mechanism of the source analysis, interested can continue to pay attention toCarson_Ho android Development Notes

Thumb up, please! Because your encouragement is the biggest power that I write!


Welcome to follow Carson_ho on wechat