The message mechanism of Android learning notes

Source: Internet
Author: User
Tags message queue

The message mechanism of Android mainly refers to the operating mechanism of handler and the working process of MessageQueue and Looper accompanying handler.

1. Why use handler?

Android provides access to the UI only in the main thread, and throws an exception if the UI is accessed in a child thread. At the same time, Android does not recommend time-consuming operations in the main thread, or it can cause the program to be unresponsive or ANR. So time-consuming work can only be left to the child threads to do, but the child thread does not have direct access to the UI, in order to resolve this contradiction, Android provides handler. The main function of handler is to switch a task to a specified thread to execute. For example, we create handler in the main thread, and after the child threads have performed the time-consuming tasks, we can switch the update UI operation to the main thread by handler.

2. Why does the system not allow access to the UI in child threads?

because Android UI controls are not thread-safe, concurrent access in multiple threads can cause UI controls to be in unexpected state.

3.Handler and Messagequeue,looper

The message mechanism of Android mainly refers to the operation mechanism of handler, the handler operation needs the support of message Queue (MessageQueue) and message loop (Looper).

The internal storage structure of Message Queuing is not a real queue, but a single-linked list . Message Queuing is simply a storage unit of a message that cannot process a message, and Looper is the one that handles the message. Looper will be infinite loop to see if there is a message, if there is, to deal with, otherwise have been waiting.

handler is created using the current thread 's looper to construct the message circulatory system, and if the current thread does not have Looper, an error is given (sometimes, a looper can be specified through the constructor). The looper of this current thread is obtained through threadlocal. Threadlocal is not a thread, it is a data store class inside a thread that can store data and fetch data in a specified linear.

4.MessageQueue Working principle

The MessageQueue consists of two operations: insert and read, respectively, corresponding to Enqueuemessage and next two methods. Enqueuemessage is inserting a message into the message queue, and next is removing a message from the message queue and deleting it from the message queue. As mentioned earlier, the internal implementation of Message Queuing is a iyge single-linked list, which has an advantage over insertions and deletions.

Note here that the next method is an infinite loop, and if there is no message in the message queue, then the next method will block and when a new message arrives, it will return the message and delete it from the single linked list.

How the 5.Looper works

(1 ) Looper will continue to see if there is a message from the MessageQueue, if there is, it will be processed immediately, otherwise it will be blocked.

here's how to create looper for the current thread:

New Thead ("Thread1") {  @override   publicvoid  run ()  {    Looper.prepare ( );    Handler Handler=new  Handler ();    Looper.loop ();  }}

Note that the message circulatory system does not really work until the Looper loop method is called.

The loop method calls MessageQueue's next method to get the message, and when there is no message, the next method blocks, causing the loop method to block. After Looper obtains the message, it invokes the DispatchMessage method of the handler object, which is executed in the handler used when the Looper was created, so that the code logic is switched to the specified thread.

The Loop method is a dead loop, and the only way to jump out of a loop is to return null with the next method of MessageQueue. When Looper's Quit method is called, it calls MessageQueue's quit or Quitsafely method to notify the message queue to exit, and its next method returns Null when the message queue is marked as exited.

(2) Looper can also exit, the Main method is quit and quitsafely. The former will exit Looper directly, while the latter simply sets a tag and then exits the message queue after the message has been processed. After the looper exits, handler can no longer send the message successfully, and its Send method returns FALSE.

(3) After the Looper is created in the child thread , the quit method should be called when all things are finished to terminate the message loop, otherwise the child thread will remain in the waiting state .

How the 6.Handler works

The main task of handler is to send and receive messages. The message is sent through the method of post and the method of send, the POST method is finally implemented by the method of send.

Handler sends a message simply by inserting a message into the message queue and then MessageQueue the message to Looper with the next method, and finally looper the message to handler processing. That is, the handler DispatchMessage method is called.

public void DispatchMessage (Message msg) {
if (msg.callback!=null)
{
Handlecallback (msg);
}
Else
{
if (mcallback!=null)
{

if (Mcallback.handlemessage (msg))
{
Return
               }

Handlemessage (msg);
}
}

The Msg.callback object here is actually a runnable object, which is the runnable parameter passed by the handler post method.

The mcallback corresponding class implements the callback interface. When we do not want to derive handler subclasses and override their handlemessage methods, they can be implemented by callback.

The message mechanism of Android learning notes

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.