Android messaging system model and handler Looper

Source: Internet
Author: User
Tags message queue

Http://www.cnblogs.com/bastard/archive/2012/06/08/2541944.html

Android messaging system model and handler Looper

As a large number of handler used in Android, the combination of thread makes it a large number of use forms and methods,

Let me temporarily feel this thing some iffy, unclear why, this is what kind of existence? by online

Information and source of learning, the handler is almost clear, and now summarize the results of this study.

A handler function and concept

learn from official documentation Handler The general concept is:

Handler enables you to send and process messages, as well as runnable objects; Each handler object corresponds to a thread and

Thread's message queue. When you create a handler, it is bound to the thread's message queue, and then you can

Passes messages and Runnable objects to the message queue and exits from the message queue after the message is executed.

The function of handler is to dispatch messages and runnable objects to be executed, and to make the actions executed in different threads.

When a process is created in an application, its main thread runs the message queue (MessageQueue) specifically,

Top-level application-related objects such as: Activity,broadcastreceiver,windows, etc., you can create your

Thread, interacting with the main thread-through handler, the method of interaction is via post or SendMessage.

However, in your new thread, the given message or runnable will be dispatched and processed at the appropriate time.

(That is, it will not be processed immediately--blocking).

This is the general meaning of the description of the handler in the official document (the English comparison is not correct in the bad translation).

from these documents, we probably learned that Handler What you've done:

    • Running on a thread, sharing the thread's message queue;
    • Receive messages, dispatch messages, distribute messages, and process messages;
    • Implement asynchronous processing of messages;

Basically it's about the news, so what is this actually doing?

--Establish a message processing model/system.

  

To learn handler, see it must be related to the message, you may need to familiarize yourself with the composition of the message system and simple principle.

Let's learn the fundamentals of the messaging system.

The basic principle and composition of the two-message system

The establishment of a generic message system model roughly consists of the following parts:

L Message Prototype

L Message Queuing

L Send a message

L message loop

L Message Acquisition

L Message Distribution

L Message Processing

The approximate model diagram is as follows:

    

The message system model typically includes the above seven parts (message prototypes, Message Queuing, message sending, message loops, message fetching,

Message dispatch, message processing). The real core is Message Queuing and message loops, and the rest revolves around these two parts.

From the analysis of the previous document, we know that handler is the system model used to build the message processing, and here the basic message

How does handler include these seven parts compared to the system model?

In Android, these six parts are abstracted into four separate sections:

Handler,message,messagequeue,looper;

    • The message is a prototype of the messages, containing the message description and data,
    • MessageQueue is the message queue,
    • Looper Completing the message loop
    • Handler is to harness the entire message system model, commanding Message,messgequeue and Looper;

  

Handler is able to implement the message system model, so how does it work, and here's how it works and how it works.

Analysis of working principle of three Handler

To understand how handler works, take a look at what the hierarchical framework of this system model consists of.

      

Looper :

Implement thread message loop and message dispatch, by default thread is no looper for this message loop;

Need to be active to create, and then start Looper loop loop, and external interaction through the handler;

MessageQueue :

Message Queuing, held by Looper, but the addition of messages is done through handler;

  

Both the message loop and the message queue belong to thread, and handler itself does not have looper and MessageQueue;

However, the establishment and interaction of the message system is the thread will give Looper and MessageQueue to a handler maintenance to establish a message system model.

So the core of the message system model is looper. Message loops and message queues are all created by Looper,

And the key to building handler is this looper.

A thread can correspond to multiple handler at the same time, and a handler can belong to only one thread at a time. Which handler belongs to?

The thread depends on the handler that is established in that thread.

In a thread looper is also the only, a thread corresponding to a looper, the establishment of handler Looper from which thread,

Which thread the handler belongs to.

Therefore, the establishment of the thread message system, that is, the thread of the Looper to handler to take care of, implement the message system model, complete the asynchronous processing of messages.

  

The relationship between handler and thread and Looper can be expressed in the following diagram:

    

Handler is not equal to thread, it must pass the thread's looper and its MessageQueue,

Used to implement the thread message system model, attached to the thread.

When the thread establishes handler:

Make handler meet the requirements of the message system, Looper and MessageQueue in thread are given to handler to be responsible for maintenance.

Build in thread Handler , the following tasks need to be done:

L get Looper of thread to handler member variable reference maintenance;

L get MessageQueue to handler member variable reference maintenance through Looper.

Then after the message system model is established, it runs according to the message system,

From handler, the message distribution message is sent, and the interaction with this thread's messaging system is done by handler.

Message sending and dispatching interface:

L Post (runnable) message, runnable is a message callback, which is triggered by message loop callback function execution;

L sendMessage (message) messages, which are processed by messages in the message loop distribution.

L DispatchMessage Dispatch message, if post or with callback function executes callback function, otherwise execute

The handlemessage of the message handler function handler (usually derived classes are overridden).

This is how handler implements the thread message system model.

The following is a detailed analysis of how to implement the message system model to run.

Four handler realization Process analysis

We know that handler is the shell of a messaging system that belongs to a thread and wraps the thread's Looper

and its MessageQueue; interacting with the outside (within or between threads), receiving dispatch and processing messages,

The core of the message system model is looper.

Let's look at how handler is built to run, with MSG as an example, runnable is essentially the same.

1 Establishment of the handler

The handler only belongs to a thread, and handler is required to obtain the thread's looper when it is established in a thread

And its MessageQueue, the key to establish handler is the source of Looper.

Handler provides several constructors but is essentially the same:

incoming Looper by external: current thread or other thread

Public Handler (Looper Looper) {
        Initialize the build message system parameter = looper; = looper.mqueue; = null; }

obtained from the current thread: determined by the thread that created the handler

Public Handler () {
        Initialize the build message system parameter = Looper. Mylooper(); = mlooper.mqueue; mylooper() { return sthreadlocal.get (); }

Either way, we know that thread does not establish a message loop Looper instance by default.

To implement a message loop, you must ensure that the thread's looper is established. How to ensure it?

Looper provides a static function:

public static void Prepare () {     if (sthreadlocal.get () = null) {              throw new RuntimeException ("Only one Looper may b E created per thread ");     }     sthreadlocal sthreadlocal = new threadlocal<looper> ();

It was strange and confusing to see the beginning of this place:

Looper a separate class that does not belong to a thread, and the function that creates looper here is static,

belongs to the entire Looper class; After the Looper is created, it is given to the static member variable sthreadlocal save, get

Sthreadlocal.get (), then a static variable belongs to the entire class, and the property change is always valid. Once created

Sthreadlocal.get () is never equal to null!

  

and the thread and Looper is the only corresponding, then here is not all the thread is the same looper, impossible!

So surely this threadlocal is a mystery. Online Search:

  ThreadLocal:

Maintains thread variables, provides a separate copy of the variable for each thread instance that uses the variable, and each thread can use the variable independently.

without affecting each other. (For more information: http://blog.csdn.net/qjyong/article/details/2158097)

So when each thread calls Looper.prepare, it is created as its only looper.

To establish a handler, you need to create the looper of the thread before you can establish the message system model. Through Looper we have established

The message system model on thread is handler and can be used for a series of processes of the message system.

2 message Sent

Two ways of sending messages: Post and SendMessage;

Post : for runnable objects; runnable is an interface, which is a callback function (provides the Run method)

SendMessage : for the Message object;

The following is a detailed look at the process through the code:

Public Final Boolean post (Runnable R) {       return  sendmessagedelayed (Getpostmessage (R), 0);} Public Final Boolean sendMessage (Message msg) {    return sendmessagedelayed (msg, 0);}

When you see post and SendMessage sending messages, only the objects are different, runnable and message;

But it's actually all in the form of a message.

This is different from the message mechanism I usually understand:

Usually the post message is returned when the message is added to the message queue and not immediately executed, and the send message is immediately executed waiting for the message to be executed.

Here either post or send puts the message into the message queue and returns immediately, waiting for the message loop to get the message to be executed.

Here are a number of message-sending methods to specify the execution time and order of messages, which can be viewed in the source code.

The order of message execution depends on the order in which messages in the message queue are arranged.

Here's a look at the code that adds the message to the message queue after the message is sent:

by Handler called MessageQueue of the Enqueuemessage Method:

Enqueuemessage (Message msg, long when) {              Message p = mmessages;              if (p = = NULL | | when = = 0 |-when < p.when) {                 msg.next = p;                 Mmessages = msg;              }              else {
Message prev = null; while (P! = null && p.when <= when) { prev = p; p = p.next; } Msg.next = Prev.next; Prev.next = msg; } ......  }

  

You can see that the messages are added to the MessageQueue in chronological order;

Now the message is added to the message queue to be stored, the message is not processed, and the next step must be how to dispatch the message and process the message.

3 Message Distribution

Establish Thread The message loop consists of Looper complete, there is a message to dispatch the dead loop:

public static void Loop () {       MessageQueue queue = me.mqueue;       while (true) {              Message msg = Queue.next ();//might block              if (msg! = null) {                     if (Msg.target = = null) {                            / /No Target is a magic identifier for the quit message.                            return;                     }                     Dispatch messages to Target (Handler) msg.target.dispatchMessage (msg);  Recycle msg to Msgpool                     msg.recycle ();              }       } }

  

Here we see that the message distribution is done by the target of the messages, what is this target? is a handler.

The message system is used by handler to interact with the outside and distribute the message. You can see that without this handler, the message loop will end.

the message was distributed by Looper through Handler Complete:

public void DispatchMessage (Message msg) {       //First Judge Runnable object       if (msg.callback! = null) {              Handlecallback ( msg);       }       else {              //The entire message system's callback function can not implement itself handler              if (mcallback! = null) {                     if (Mcallback.handlemessage (msg)) {                            return;                     }              }
Message processing is usually given to handler derived class Handlemessage (msg); } }

This enables asynchronous processing of messages through the dispatch of messages.

4 Message Prototypes

There are two ways to see the message sent in front of you:

Post (Runnable object), SendMessage (Message object), and the middle is through the message object

Saved in the MessageQueue. The message is then handled differently when it is dispatched. If the Message object is SendMessage

With the Runnable object attached, there is no difference between post and SendMessage. So the two approaches are well understood and basically consistent, and the way they are handled is different.

  

In the message system model, what are our real message prototypes, all of which have those features, and below we look at the message in the end

Contains those things that can effectively help us to use the message system to complete a number of tasks and processing.

Message Message Prototypes:

Public final class message implements Parcelable {       //Identity message public       int;       int flags;       long when;             Pass simple data public      int arg1;       public int arg2;           Pass more complex Data Objects public object       obj;       Bundle data;       Target for processing messages Handler       Handler target;          The Runnable object Runnable callback is executed when the message is distributed       ;         Make the message form a linked list message       next;       Create a message pool, recycle MSG to avoid duplication of creation cost-saving       private static Message SPool;       private static int spoolsize = 0;       private static final int max_pool_size = 10; }

  

See a rich range of properties to describe the message, choose which attributes to use to describe the message for the specific problem.

When you get a new Message object, the message provides the obtain method: avoid ourselves from assigning a new object to the message,

Obtained through obtain, may be obtained from the messagepool, saving overhead.

Let's take a look at this Messagepool how it's built:

Usually when the message is processed, the message is basically in a useless state to release the recycle. For objects that require frequent creation of releases,

Creating and releasing instances of the class is overhead, too often making the overhead worse, and it is likely that a message like this will be created frequently.

So we can save the created objects in a Pool after we've run out of them, so that we could reuse the savings and create the release cost frequently.

How was it built? Must be done after the message has been processed.

Messagepool Establish:

public static void Loop () {       while (true) {              //Dispatch message              msg.target.dispatchMessage (msg);              The message is processed and recycled msg.recycle (); }} public     void Recycle () {       ///Recycle message Global Messagepool       if (Spoolsize < max_pool_size) {           next = SPool;           SPool = this;           spoolsize++;}       }

Application of five Handler

Above this is the whole handler function and the establishment of the message system model.

The use is also very simple, although there are many ways, but as long as the understanding handler is built on Looper, the implementation of thread

The message system processes the model and realizes the asynchronous processing of the message, and I think there is nothing incomprehensible about the basic application of handler.

Other aspects can go to see the source.

Handler is very simple to use, the key is how to use the asynchronous processing of messages, to reasonably complete our

Features and tasks are required. For a thread, we use several handler for asynchronous processing, or we can create a new thread,

Through the handler to realize the asynchronous processing of messages and so on, the application scenario a lot of how to use the reasonable, this is not experience.

As for how to use, many examples of the source code can look at asyncqueryhandler This class, of which two threads,

Complete the query work by handler to have message passing between threads. It feels good to use and it's ingenious.

Reference article: http://blog.csdn.net/maxleng/article/details/5552976

Android messaging system model and handler Looper

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.