Android Handler, message full resolution, take you from the source point of view to thoroughly understand

Source: Internet
Author: User
Tags final prepare thread

Also because of the weekend night to watch TI3 competition, has not found time to write a blog, leading to have been a long time not updated. Ashamed! You'll get back to your schedule and try to make sure you write every week. Here is also the first congratulations from Sweden's Alliance team won the TI3 champion, hope that the Chinese team will be able to rise next year!

Getting started, we all know that the Android UI is thread-safe, and that if you try a UI operation in a child thread, the program can crash. Believe that everyone in the day-to-day work will often encounter this problem, the solution should also have been known to the heart, that is, create a Message object, and then with the help of handler sent out, after the Handlemessage in handler () method to get the message object that you just sent, and then do the UI action here without crashing again.

This kind of processing is called asynchronous message processing thread, although I believe everybody can use, but do you know what is the principle behind it? Today we are going to delve into the secrets behind handler and message.

First look at how to create a handler object. You might be wondering, what's the good thing about creating handler, just a new one? Yes, but even if it's just a simple new one, there are a lot of places to note, we try to create two handler objects in the program, one in the main thread, one in the child thread, and the code looks like this:

public class Mainactivity extends activity {  
          
    private Handler handler1;  
          
    Private Handler Handler2;  
      
    @Override
    protected void onCreate (Bundle savedinstancestate) {  
        super.oncreate (savedinstancestate);  
        Setcontentview (r.layout.activity_main);  
        Handler1 = new Handler ();  
        New Thread (New Runnable () {  
            @Override public
            void Run () {  
                handler2 = new Handler ();  
            }  
        }). Start ();  
    }  
      

If you run the program now, you will find that the handler created in the child thread will cause the program to crash, and the error message for can ' t create handler inside thread ' has not called looper.prepare ( ) 。 To say that you cannot create handler in a thread that does not invoke Looper.prepare (), then we try to invoke Looper.prepare () in the child thread, as shown in the following code:

New Thread (New Runnable () {  
    @Override public
    void Run () {  
        looper.prepare ();  
        Handler2 = new Handler ();  
    }  
). Start ();

Sure enough this will not collapse, but only satisfied with this is obviously not enough, we look under the handler source code, to find out why not call Looper.prepare () will not do it. The parameterless constructor of the handler is as follows:

Public 

Handler () {  
    if (find_potential_leaks) {  
        final class<? extends handler> Klass = GetClass ();  
        if ((Klass.isanonymousclass () | | | klass.ismemberclass () | | klass.islocalclass ()) 

&&  
                ( Klass.getmodifiers () & modifier.static) = = 0) {  
            log.w (TAG, "the following Handler class should be STATIC or leaks Might occur: "+  
                klass.getcanonicalname ());  
        }  
    }  
    Mlooper = Looper.mylooper ();  
    if (Mlooper = = null) {  
        throw new RuntimeException (  
            "Can" t create handler inside thread that is has not called Loope R.prepare () ");  
    }  
    Mqueue = Mlooper.mqueue;  
    Mcallback = null;  
}

As you can see, the Looper.mylooper () method is invoked on line 10th to obtain a Looper object, and if the Looper object is empty, a Run-time exception is thrown, which is the error of the Can ' t create handler inside thread That is has not called looper.prepare ()! When will the Looper object be empty? This will take a look at the code in Looper.mylooper (), as follows:

public static final Looper Mylooper () {return  
    (Looper) sthreadlocal.get ();  
}

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.