Android message mechanism Simple explanation

Source: Internet
Author: User
Tags message queue

First, the principle

1. Message

Message, understood as a data unit for communication between threads. For example, when a background thread needs to update the UI after processing the data, it can send a message to the UI thread that contains the updated information.

2. Message Queue

Message queues, which are used to store messages posted via handler, in advance of first out execution.

3. Handler

Handler is the primary processor of the message, which is responsible for adding messages to the queue and processing messages in message queues.

4. Looper

The loop, playing the role of the bridge between message queue and handler, loops through and gives the corresponding handler for processing. The normal thread is also converted to a looper thread (the Looper thread is actually a looping thread).

Code:

 
  
  
The code is as follows Copy Code
public class Looperthread extends Thread {public

 

Handler Mhandler;

   @Override public

   Void Run () {

       //Initialize the current thread to Looper thread

       looper.prepare ();

       

       // ... Other processing, such as instantiating Handler

        Mhandler = new Handler () {public

             void Handlemessage (msg) {

                 //process incoming M Essages here

             }

         ;

 

       Start the loop processing of Message Queuing

       looper.loop ();

   }

As shown in figure:

5. Thread

UI thread is usually the main thread, and the Android launcher creates a message Queue for it.
Each thread can contain a Looper object and a MessageQueue data structure. In your application
In order, you can define subcategories of handler to receive messages sent by Looper.

To sum up, the relationship between the message Queue, Handler, and looper them is as follows:

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.