Android learning notes-Handler message transmission mechanism for event processing, androidhandler

Source: Internet
Author: User

Android learning notes-Handler message transmission mechanism for event processing, androidhandler

Summary: a summary and problem record of the Android Handler message passing mechanism

 

Purpose of Handler message transmission mechanism:

1. implement inter-thread communication (for example, the Android platform only allows the main thread (UI thread) to modify the UI components in the Activity, in actual development, a new thread needs to change the interface component attributes. In this case, there is a way to notify the main thread to update the UI ). The Handler message transmission mechanism can be used to transmit messages between threads.

2. asynchronous message processing.

 

Implementation of the Mechanism: (working principle involves Handler, logoff, Message, MessageQueue (Message Queue); Code is divided into Message Receiver and sender)

Description of the principle (I have limited understanding. For more information about Handler, see this article ):

Handler can send a Message to MessageQueue or process the Message received from logoff.

Message object, transmitted throughout the mechanism.

MessageQueue is a queue that manages messages in FIFO mode.

Logoff manages MessageQueue, which distributes the messages obtained from MessageQueue to the corresponding Handler.

 

Schematic:

 

Note:

1. Handler is built on logoff to implement the Thread message system processing model and Implement Asynchronous Message Processing;

2. MessageQueue will create an association during logoff () constructor) initialization;

3. A thread can have at most one logoff object (defined in this );

4. the main thread (UI thread) system has helped initialize a logoff object (for simple analysis, see the main thread source code for detailed analysis), so the program can directly create a Handler; the developer must first create a logoff object and start the thread. loop () before sending messages to the thread's message queue.

 

Logoff source code reference:

The prepare () method ensures that each thread has at most one logoff object. The loop () method uses an endless loop to continuously retrieve messages in MessageQueue, and distributes the acquired messages to the corresponding Handler for processing.

1 // create and associate MessageQueue2 private Looper (boolean quitAllowed) {3 mQueue = new MessageQueue (quitAllowed); 4 mThread = Thread. currentThread (); 5}
1 // one thread can have at most one logoff. Call the prepare () method to create the logoff object 2 public static void prepare () {3 prepare (true ); 4} 5 6 private static void prepare (boolean quitAllowed) {7 if (sThreadLocal. get ()! = Null) {8 throw new RuntimeException ("Only one Looper may be created per thread"); 9} 10 sThreadLocal. set (new LOD (quitAllowed); 11}
1/** 2 * Initialize the current thread as a looper, marking it as an 3 * application's main looper. the main logoff for your application 4 * is created by the Android environment, so you shoshould never need 5 * to call this function yourself. see also: {@ link # prepare ()} 6 */7 // method used by the main UI thread to initialize the logoff object call 8 public static void preparemainloe () {9 prepare (false ); 10 synchronized (Looper. class) {11 if ( Smainlogoff! = Null) {12 throw new IllegalStateException ("The main loginhas already been prepared."); 13} 14 smainlogint = mylogin(); 15} 16}
1/** 2 * Run the message queue in this thread. be sure to call 3 * {@ link # quit ()} to end the loop. 4 */5 public static void loop () {6 final Looper me = myloal (); 7 if (me = null) {8 throw new RuntimeException ("No loal; loal. prepare () wasn' t called on this thread. "); 9} 10 final MessageQueue queue = me. mQueue; 11 12 // Make sure the identity of this thread is that of the local process, 13 // And keep track of what that identity token actually is.14 Binder. clearCallingIdentity (); 15 final long ident = Binder. clearCallingIdentity (); 16 17 // uses an endless loop to get the Message from MessageQueue and send it to the corresponding Handler18 for (;) {19 Message msg = queue. next (); // might block20 if (msg = null) {21 // No message indicates that the message queue is quitting.22 return; 23} 24 25 // This must be in a local variable, in case A UI event sets the logger26 final Printer logging = me. mLogging; 27 if (logging! = Null) {28 logging. println (">>>>> Dispatching to" + msg.tar get + "" + 29 msg. callback + ":" + msg. what); 30} 31 32 final long slowDispatchThresholdMs = me. mSlowDispatchThresholdMs; 33 34 final long traceTag = me. mTraceTag; 35 if (traceTag! = 0 & Trace. isTagEnabled (traceTag) {36 Trace. traceBegin (traceTag, msg.tar get. getTraceName (msg); 37} 38 final long start = (slowDispatchThresholdMs = 0 )? 0: SystemClock. uptimeMillis (); 39 final long end; 40 try {41 msg.tar get. dispatchMessage (msg); 42 end = (slowDispatchThresholdMs = 0 )? 0: SystemClock. uptimeMillis (); 43} finally {44 if (traceTag! = 0) {45 Trace. traceEnd (traceTag); 46} 47} 48 if (slowDispatchThresholdMs> 0) {49 final long time = end-start; 50 if (time> slowDispatchThresholdMs) {51 Slog. w (TAG, "Dispatch took" + time + "ms on" 52 + Thread. currentThread (). getName () + ", h =" + 53 msg.tar get + "cb =" + msg. callback + "msg =" + msg. what); 54} 55} 56 57 if (logging! = Null) {58 logging. println ("<Finished to" + msg.tar get + "" + msg. callback); 59} 60 61 // Make sure that during the course of dispatching the62 // identity of the thread wasn't passed upted.63 final long newIdent = Binder. clearCallingIdentity (); 64 if (ident! = NewIdent) {65 Log. wtf (TAG, "Thread identity changed from 0x" 66 + Long. toHexString (ident) + "to 0x" 67 + Long. toHexString (newIdent) + "while dispatching to" 68 + msg.tar get. getClass (). getName () + "" 69 + msg. callback + "what =" + msg. what); 70} 71 72 msg. recycleUnchecked (); 73} 74}

The principle is summarized here, and the following describes how to implement it in the code.

 

Code example (only one implementation, which can be summarized in more Handler usage ):

1. The message receiver thread first calls Looper. prepare () to create a Looper object, then creates a Handler object, and defines the method for processing the message. Next, it calls Looper. loop () to start Looper.

 1 class CallbackThread extends Thread { 2     public Handler mHandler; 3          4     public void run() { 5         Looper.prepare(); 6         mHandler = new Handler() { 7             @Override 8             public void handleMessage(Message msg) { 9                 if (msg.what == 123) {10                     Toast.makeText(MainActivity.this, "get message!", Toast.LENGTH_SHORT).show();11                 }12             }13         };14         Looper.loop();15     }16 }

2. The message sender's thread sends a message to the Handler object of the receiver's thread by calling Handler-related methods. Available methods include:

1 callbackThread = new CallbackThread (); 2 callbackThread. start (); 3 4 // send an empty message 5 callbackThread. mHandler. sendEmptyMessage (123); 6 7 // create a Message to send 8 Message msg = new Message (); 9 msg. what = 123; 10 callbackThread. mHandler. sendMessage (msg );

The above is the Handler's learning summary, followed by a record of problems encountered during the learning process.

 

Problem records

1. In the sample code, the thread that receives the message first calls lorule. prepare (), creates a Handler to implement the message processing method, and then lorule. loop (). Why?Prepare-> Handler-> LoopIn this order? Can it be changed?

A: The order cannot be changed. First, prepare must Be before loop, because the source code comment of the prepare () method contains such a sentence (Be sure to call * {@ link # loop ()} after calling this method), Then click it (because I didn't see the source code ......). There are two more orders, right? Try them one by one. Handler-> prepare-> loop does not work, because the sent message is not received. Prepare-> loop-> Handler is not allowed, which causes the APP to exit. My (zhao) chao (wang) solution (shang) is a Handler. to work normally, we must first ensure that there is a loy object (why? Is there a message queue before sending messages ?), Therefore, prepare is required to create a logoff object first, and then logoff. loop () uses an endless loop to retrieve messages, and blocks messages when no messages exist. In this way, the Code placed after it-the code that creates Handler will not be executed, when the sendMessage () method of the Handler object is called, NullPointerException is generated, as shown in the following figure (AV image quality ):

 

 

2. It does not mean that only the UI thread can operate on the UI component. Why does the subthread still display the Handler object when the code above places it between prepare and loop?

A: First, the subthread cannot directly use Toast. If Toast is not displayed, an error is reported ...... then I went online and found this article. I just came to the conclusion that "Toast may belong to modifying the UI "??? Which of the following meanings ??? So I looked for it again and found it. Oh, my God! If Toast has been used for so long, isn't it a UI update operation? Maybe, as zhihu said, "The Toast operation is window, it does not belong to the management category where the checkThread throws the main thread and cannot update UI exceptions "? The amount of information is too large. I have not understood the limited capabilities. I will first check the suspected records // Todo. In short, we now know that Toast can be used in subthreads with the help of logoff.

 

3. Isn't it resource-consuming to use an infinite loop to retrieve messages?

A: No. Read this article for details. Wait get. dispatchMessage (), otherwise queue. next () will be blocked until the timeout time is exceeded.

 

4. The main thread logoff also calls loop (), will it also block?

A: There will also be blocking, but it will not be stuck. In fact, it is the same as problem 3. If MessageQueue has no message, it will be blocked and sleep. Then it will be awakened by the handle write operation epoll. wait. Reference: zhihu question, CSDN article (although the title and conclusion of the article are contradictory ).

 

5. How is the blocking of queue. next () implemented?

A: refer to the link in 3, 4. Keyword: Linux pipe/epoll mechanism, nativePollOnce () method in queue. next () of loop.

 

Feeling: It took me one night to add half an afternoon to my first blog, mom! Why are those bosses so productive. There are actually more problems, but some of them forget to record them. Some of them are too immature, and there are still issues that have not been found ...... it's getting worse and harder, and there's no sense of being open-minded at all ??? I know too little about it. I can't digest so many new things at a time, and my study notes are also messy. After all, I wrote my blog for the first time and learned it slowly. The road to Android is long!

 

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.