Android is using handler to implement message distribution mechanisms (two)

Source: Internet
Author: User
<span id="Label3"></p><p><p>Before you start this article. first, We summarize the first two articles handler, Looper and MessageQueue like some key points:</p></p><p><p>0) before you create a thread handler, you must call Looper.prepare (), Create a thread-local variable looper, and then call Looper.loop () into the round Robin.</p></p><p><p>1) when handler is created, it is able to call Handler's Sendmessageattime method to send a message. instead, the Enqueuemessage method that calls MessageQueue is actually called. Put the corresponding message in the message Queue.</p></p><p><p>2) Each thread has only one looper, and this looper is responsible for MessageQueue rotation when getting to the Message. The handler.dispatchmessage is called to Distribute.</p></p><p><p></p></p><p><p>From the above three points, we can probably see the use of handler Flow.</p></p><p><p>Today we'll start with the news from where we started. Is the Enqueuemessage method of handler, the code is as Follows:</p></p><p><p></p></p><pre code_snippet_id="499327" snippet_file_name="blog_20141028_1_3554250" name="code" class="java"><pre code_snippet_id="499327" snippet_file_name="blog_20141028_1_3554250" name="code" class="java"> Private Boolean enqueuemessage (MessageQueue queue, Message msg, long uptimemillis) { msg.target = this; If (masynchronous) { msg.setasynchronous (true); } return queue.enqueuemessage (msg, uptimemillis); }</pre></pre><br>This method mainly does two things:<p><p></p></p><p><p>1) set Msg.target as the current handler object</p></p><p><p>2) call the Enqueuemessage method of MessageQueue</p></p><p><p>So. In fact, It's Here. Put the message object in the messages Queue.</p></p><p><p>Speaking of messagequeue, we must first make it clear that this message queue is actually a list of the structure of a string one.</p></p><p><p>The initialization of its queue is not done in the Java layer. instead, The JNI layer is implemented using C + +.</p></p><p><p></p></p><p><p>We can look at several native methods of its definition, such as the Following:</p></p><p><p></p></p><pre code_snippet_id="499327" snippet_file_name="blog_20141028_2_9178654" name="code" class="java"><pre code_snippet_id="499327" snippet_file_name="blog_20141028_2_9178654" name="code" class="java"> Private native static long Nativeinit (); Private native static void Nativedestroy (long ptr); Private native static void nativepollonce (long ptr, int timeoutmillis); Private native static void Nativewake (long ptr); Private Native Static Boolean nativeisidling (long ptr);</pre></pre><br>and its constructors such as the Following:<p><p></p></p><p><p></p></p><pre code_snippet_id="499327" snippet_file_name="blog_20141028_3_3091974" name="code" class="java"><pre code_snippet_id="499327" snippet_file_name="blog_20141028_3_3091974" name="code" class="java"> MessageQueue (boolean quitallowed) { mquitallowed = quitallowed; Mptr = Nativeinit (); }</pre></pre><br><p><p></p></p><p><p>here, We do not enter its code in the JNI layer, the water is too deep.</p></p><p><p>Let's take a look at the Java layer. In the Enqueuemesage method of the Messageenqueue. The basic code such as the Following:</p></p><p><p></p></p><pre code_snippet_id="499327" snippet_file_name="blog_20141028_4_1880100" name="code" class="java">Synchronized (this) {... Msg.when = when; Message p = mmessages; Boolean needwake; if (p = = NULL | | when = = 0 | | When < p.when) {//New head, Wake up the event queue if Blocked. Msg.next = p; Mmessages = msg; Needwake = mblocked; } else {//Inserted within the middle of the Queue. Usually we don ' t have to wake//up the event queue unless there are a barrier at the head of the the queue The message is the earliest asynchronous message in the Queue. Needwake = mblocked && P.target = = null && msg.isasynchronous (); Message prev; For (;;) {prev = p; p = p.next; if (p = = NULL | | When < p.when) {break; } If (needwake && P.isasynchronous ()) {needwake = false; }} Msg.next = p; Invariant:p = = Prev.next Prev.next = msg; } ... }</pre><p><p></p></p><p><p><br></p></p>Above is the key code into the queue, and what it does is nothing more than the When FIELD. Insert the message into the appropriate location in the Queue.<p><p>Now that the message has been put in the Queue. Then the next step is to get the message in Looper's round-robin operation, and then distribute the Message. We can see in the Looper loop method that it calls the next method of Messagequeue.<br><br></p></p><p><p></p></p><pre code_snippet_id="499327" snippet_file_name="blog_20141028_5_5892478" name="code" class="java"><pre code_snippet_id="499327" snippet_file_name="blog_20141028_5_5892478" name="code" class="java"> For (;;) { message msg = Queue.next ();//might block if (msg = = Null) { //No message indicates that the message queue is Quitting. return; } This must is in a local variable with case a UI event sets the logger Printer logging = me.mlogging; If (logging! = Null) { logging.println (">>>>> dispatching to" + msg.target + "" + Msg.callback + ":" + msg.what); } Msg.target.dispatchMessage (msg);</pre></pre><br>well, obviously. Is in the next method of messagequeue, get the message, let us also go into its method to look at it.<p><p></p></p><p><p></p></p><pre code_snippet_id="499327" snippet_file_name="blog_20141028_6_5760399" name="code" class="java">Message next () {int pendingidlehandlercount =-1;//-1 only during first iteration int Nextpolltimeoutmill is = 0; For (;;) {if (nextpolltimeoutmillis! = 0) {binder.flushpendingcommands (); }//We can assume mptr! = 0 because the loop is obviously still running. The looper would not be the call of this method after the loop quits. Nativepollonce (mptr, nextpolltimeoutmillis); Synchronized (this) {//Try to retrieve the next Message. Return if Found. Final Long now = Systemclock.uptimemillis (); Message prevmsg = null; Message msg = mmessages; If (msg! = null && msg.target = = Null) {//stalled by a barrier. Find the next asynchronous message in the Queue. Do {prevmsg = msg; msg = msg.next; } While (msg! =Null &&!msg.isasynchronous ()); If (msg! = Null) {if (now < msg.when) {//Next message ' is Not Ready. Set a timeout to wake up when it was ready. Nextpolltimeoutmillis = (int) math.min (msg.when-now, integer.max_value); } else {//Got a message. mblocked = false; If (prevmsg! = Null) {prevmsg.next = msg.next; } Else {mmessages = msg.next; } Msg.next = null; If (false) log.v ("MessageQueue", "returning message:" + msg); Msg.markinuse (); Return msg; }} Else {//No more Messages. Nextpolltimeoutmillis =-1; } Process the QUIT message now, all pending messages has been Handled. If (mquitting) {dispose (); Return null; }//If first time idle, then get the number of idlers to Run. Idle handles only run if the queue is empty or if the first message//in the queue (possibly a barrier) is due to being handled in the Future. If (pendingidlehandlercount < 0 && (mmessages = = NULL | | Now < MMESSAGES.WHEN)) { Pendingidlehandlercount = Midlehandlers.size (); } if (pendingidlehandlercount <= 0) {//No idle handlers to Run. Loop and wait some more. mblocked = true; Continue } if (mpendingidlehandlers = = Null) {mpendingidlehandlers = new Idlehandler[math.max (pe Ndingidlehandlercount, 4)]; } mpendingidlehandlers = Midlehandlers.toarray (mpendingidlehandlers); }//Run the Idle Handlers. We only ever reach this code block during the first Iteration. for (int i = 0; i < pendingidlehandlercount; i++) {final Idlehandler idler = mpendingidlehandlers[i]; mpendingidlehandlers[i] = null; Release the reference to the handler Boolean keep = false; Try {keep = Idler.queueidle (); } catch (throwable T) {log.wtf ("MessageQueue", "idlehandler threw exception", t); } if (!keep) {synchronized (this) {midlehandlers.remove (idler); }}}//Reset the idle handler count to 0 so we don't run them Again. Pendingidlehandlercount = 0; While calling an idle handler, a new message could has been delivered//so go back and look again for A pending message without Waiting. Nextpolltimeoutmillis = 0; } }</pre><p><p></p></p><p><p><br></p></p>The whole code is a bit long, but we're going to get rid of some code that doesn't have much to do with our implementation, and we can see the main points:<p><p>1) is a for (;;) Cycle</p></p><p><p>2) only when the message is acquired or mquitting is true does it jump out of the loop.</p></p><p><p>3) when a message is obtained, it is inferred based on the Message.when FIELD.</p></p><p><p>From the above, we can probably understand why the next method may be blocked in the loop method. Because it is an infinite round-robin operation.</p></p><p><p>well, when we get here, we probably know the following two things:</p></p><p><p>1) in the handler sendmessageattime method, call Messagequeue's Enqueuemessage method and put the message into the Queue.</p></p><p><p>2) the Looop method in Looper. Call the next method of Messagequeue. Take the message out of the Queue.</p></p><p><p>The next third step, obviously, is to call Handler's DispatchMessage method, such as the Following:</p></p><p><p></p></p><pre code_snippet_id="499327" snippet_file_name="blog_20141028_7_9565035" name="code" class="java"><pre code_snippet_id="499327" snippet_file_name="blog_20141028_7_9565035" name="code" class="java">Msg.target.dispatchMessage (msg);</pre></pre><br>In the beginning of the article, we noticed that Msg.target is just the handler object, so logic came to handler DispatchMessage method, such as the Following:<p><p></p></p><p><p></p></p><pre code_snippet_id="499327" snippet_file_name="blog_20141028_8_6957721" name="code" class="java"><pre code_snippet_id="499327" snippet_file_name="blog_20141028_8_6957721" name="code" class="java"> public void DispatchMessage (Message Msg) { If (msg.callback! = Null) { handlecallback (msg); } Else { if ( mcallback! = Null) { if (mcallback.handlemessage (msg)) { return; } } Handlemessage (msg); } }</pre></pre><br>From the logic of the code, we need to understand what a few variable methods are all About:<p><p></p></p><p><p>1) Msg.callback</p></p><p><p>2) Mcallback</p></p><p><p>3) Handlemessage</p></p><p><p>First of all, what is msg.callback?</p></p><p><p>In the message class. We can see</p></p><p><p></p></p><pre code_snippet_id="499327" snippet_file_name="blog_20141028_9_3237592" name="code" class="java"><pre code_snippet_id="499327" snippet_file_name="blog_20141028_9_3237592" name="code" class="java">Runnable callback;</pre></pre><p><p></p></p><p><p>There are also its constructors:</p></p><p><p></p></p><pre code_snippet_id="499327" snippet_file_name="blog_20141028_10_1710073" name="code" class="java"><pre code_snippet_id="499327" snippet_file_name="blog_20141028_10_1710073" name="code" class="java"> public static Message obtain (Handler h, Runnable callback) { Message m = Obtain (); M.target = h; M.callback = callback; return m; }</pre></pre><br>is actually a runnable variable that can be put into a new thread to Run. You can define your own settings when you get a message.<p><p></p></p><p><p></p></p><p><p></p></p><p><p>So in dispatchmessage, the first is to infer whether there is a runnable to the message set callback, Fake. Run this callback method, such as the Following:</p></p><p><p></p></p><pre code_snippet_id="499327" snippet_file_name="blog_20141028_11_9102758" name="code" class="java"><pre code_snippet_id="499327" snippet_file_name="blog_20141028_11_9102758" name="code" class="java"> private static void Handlecallback (message Message) { message.callback.run (); }</pre></pre><br>so, What is the second mcallback, which is actually a handler built-in interface, such as the Following:<p><p></p></p><p><p></p></p><pre code_snippet_id="499327" snippet_file_name="blog_20141028_12_83495" name="code" class="java"><pre code_snippet_id="499327" snippet_file_name="blog_20141028_12_83495" name="code" class="java"> public interface Callback {public boolean handlemessage (Message msg); </pre></pre><br>Assuming that our handler has implemented this interface, this interface will prioritize the message when the message is Distributed.<p><p></p></p><p><p>In the ordinary case, only we want to inherit the handler class. When we implement our own defined handler, we will implement this interface, and when this interface returns true, the handler default Handlemessage method will no longer be called. conversely, it will still be called.</p></p><p><p>finally, We are the most common handlemessage method. That's How we implement the most common handler.</p></p><p><p>Same. There is no example of how to do it, see the Code:</p></p><p><p></p></p><pre code_snippet_id="499327" snippet_file_name="blog_20141028_13_1346856" name="code" class="java"> Class Looperthread extends Thread {public Handler mhandler; public void run () {looper.prepare (); Mhandler = new Handler () {public void handlemessage (Message msg) {Log. V ("Test", "Id of looperthread:" + thread.currentthread (). getId ()); Switch (msg.what) {case msg_id_1:log.v ("Test", "Toast called from Handler.send Message () "); Break Case msg_id_2:string str = (String) msg.obj; LOG.V ("Test", str); Break } } }; Looper.loop (); }} protected void onCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); LOG.V ("Test", "Id of mainthread:" + thread.currentthread (). getId ()); Looperthread looperthread = new LOoperthread (); Looperthread.start (); While (looperthread.mhandler = = Null) {} Message message = Message.obtain (loo perthread.mhandler, New Runnable () {@Override public void run () {LOG.V ( "Test", "message.callack ()"); } }); Message.what = msg_id_1; Message.sendtotarget (); LooperThread.mHandler.post (new Runnable () {@Override public void run () { LOG.V ("Test", "handler.callack ()"); } }); }</pre><br>Over here. We use the Message.obtain (Handler, Runnable) method and the Handler.post method to construct and send messages, resulting in the results such as the following:<p><p></p></p><p><p></p></p><pre code_snippet_id="499327" snippet_file_name="blog_20141028_14_9295949" name="code" class="java"><pre code_snippet_id="499327" snippet_file_name="blog_20141028_14_9295949" name="code" class="java">10-28 11:27:49.328:v/test (22009): Id of mainthread:110-28 11:27:49.328:v/test (22009): message.callack () 10-28 11:27:49 .328:v/test (22009): Handler.callack ()</pre></pre><br>well, This article ends here, I believe that the whole message of the flow of the process, there should be a sober understanding of it.<p><p></p></p><p><p></p></p><p><p></p></p><p><p><br></p></p> <p style="font-size:12px;"><p style="font-size:12px;">Copyright Notice: This article blog original articles, blogs, without consent, may not be reproduced.</p></p> <p><p>Android is using handler to implement message distribution mechanisms (two)</p></p></span>

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.