Android asynchronous messaging mechanism source code analysis && related knowledge Frequently asked questions of the face

Source: Internet
Author: User

1. The Android asynchronous messaging mechanism has the following two ways: (Asynchronous message delivery to resolve thread communication problems)

Handler and Asynctask

2, the use of handler official interpretation:

1), timed tasks: Use Handler.postdelay (Runnable R, time) to execute MSG at specified times.

2), inter-thread communication: Perform time-consuming tasks in a child thread when performing a more time-consuming operation, and then handler (the main thread) sends the results of the execution SendMessage to the UI thread to execute for the update UI.

3, Handler source analysis

First, in Activitythread.main (the application's entry function, the main thread of execution)

Seeing the No. 5401 line of code functionality is a Looper object that generates a main thread.

The 100->90 line generates the Lopper and throws it into the threadlocal.

105 marks the generated lopper as the looper of the main thread.

The 5417 feature is that the newly generated lpooer is constantly going to loop Message Queuing, which is described later in Message Queuing.

A thread can have only one lopper, the main thread is created by default at boot time, which means that we write our own thread to use the message passing mechanism, we need to generate looper and call Looper.loop to loop the message queue.

What do you see in the Looper.loop cycle?

127 See a looper there is a messagequeue,134 start is constantly take out the message from MessageQueue to 148msg.target.dispatchmessage to deal with.

135: Face Pilot

second, look at the source of the message transmission

Handler belongs to the thread it establishes. That is, if the handler is created in the main thread, then he processes the message in the main thread, and if it is established in the child thread, the processing of the message is done in the child thread.

1. We all know that there are several ways to send messages through handler:

Handler.sendmessage (msg);

Hadler.sendmessagedelayed (msg, time);

Sendemptymessage (int what);

Public final Boolean sendemptymessagedelayed (int what, long Delaymillis)

Among them, the realization of sendemptymessage

Just wrote what's in the message.

Several functions eventually become called public boolean sendmessageattime (Message msg, long Uptimemillis)

600 lines put MSG in Looper's MessageQueue.

Next look at what Enqueueumessage has done:

551 start, according to the time information carried in MSG, find the current time to execute MSG, placed in the MessageQueue team head.

How is the message executed in the message queue, which depends on the loop function

The main look at the next 148 lines, is the MSG to msg.target dispatchmessage function to execute, that Msg.target is which object?

Handler Enqueuemessage See Msg.target is handler.

So you can see that MSG is eventually executed in the handler DispatchMessage.

When you see this function, first of all, if the msg.callback is empty, the handler handlemessage will be called.

At this point handler processing the message of the entire source process analysis completed.

Third, in addition to sending messages, there are several ways to send UI and new actions in child threads.

Handler.post

View.post

Activity.runonuithread

1, Handler.post

Or call the sendmessagedelayed, look at the getpostmeassage source

The callback to see MSG is set to runnable. Again look at the above DispatchMessage source code, this time Msg.callback will not empty, go back to execute Handlecallback

Executes the Run method in runnable directly.

To summarize, that is to say, using the handler post method is equivalent to the callback msg into the queue, and then in the removal of MSG, the direct call of the callback run method.

Note : Google suggests that when writing a message, it's best to use Message.obtain () or handler.obtainmessage () to get the current Looper message instead of going to new Message, the advantage of this is that Message.obtain () Gets a message object from the messaging pool, and if it is empty in the message pool, a new message is instantiated using the constructor method, which facilitates the use of the message resource. MSG can also be better recycled by the recycling pool .

2, View.post

is called the handler post method, so the same previous process.

3, Activity.runonuithread

See the implementation of the function is to see if the current thread is a main thread, if the direct execution of the Run method, no, call handler's Post method, the comment parsing is also clear.

Add: Look at several member variables of message

We can set the value of the above variables when we pass the message (4 reference http://blog.csdn.net/ahuier/article/details/17012005 below)

1) arg1 and arg2 are all message-like data used to pass some lightweight storage int types, such as progress bar data. This data is reproduced through bundles, and the reader can review the source code research.

2) obj is an object of the message's own type, used to pass some objects. Maximum compatibility avoids the alignment of type conversions, and so on.

3) ReplyTo is used when communicating as a thread.

4) What user-defined message code allows the recipient to identify the type of message, Int.

Four, often asked questions related to the surface.

1. Does looper.loop always go to loop when the message is empty?

Answer: https://www.zhihu.com/question/34652589

(The contents of the connection, it is strongly recommended to look at the full answer, written well) Here it involves Linux pipe/e poll mechanism, simply said that in the main thread of the MessageQueue no message, it is blocked in the Loop Queue.next () in the Nativepollonce () method, at this time the main thread will release the CPU resources into hibernation until the next message arrives or a transaction occurs, The main thread is awakened by writing data to the pipe's writing end. The epoll mechanism used here is an IO multiplexing mechanism that can monitor multiple descriptors at the same time, when a descriptor is ready (read or write ready), immediately notifies the corresponding program to read or write operations, essentially synchronous I/O, that is, read and write is blocked. So, the main thread is dormant most of the time and does not consume a lot of CPU resources.

2. What is the difference between SendMessage and post?

I want to read the analysis above, and naturally I will.

3. Who is Msg.target?

Same 2

Android asynchronous messaging mechanism source code analysis && related knowledge frequently asked questions

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.