Handler series creation sub-thread handler

Source: Internet
Author: User

In the previous article I described how the handler mechanism works, by default, the Activitythread class creates the Looper and message queues for our main thread, so when you create a handler and then send a message, Both the rotation and handle of the message are made on the UI thread. This condition belongs to a child thread that sends a message to the main thread, notifying the main thread to update the UI ... Wait, then in turn, how can the main thread send a message to the child thread, notifying the child thread to do some time-consuming logic??

Prior to learning we know that Android's messaging mechanism follows three steps:

1 Creating the Looper of the current thread

2 Creating the handler of the current thread

3 Loop method that invokes the current thread Looper object

Friends who have read the previous article will notice that this article specifically highlights the " current thread ." Yes, many of the things we have studied before are Android, we have done, for example: Create the main thread of the Looper, the main thread of the message queue ... Even the handler we use is the main thread. So if I want to create a non-main thread of the handler and send messages, processing messages, this series of operations we should do that??? Do not do, cold ~ ~ ~ What meaning??? According to gourd painting scoop, still follow the above three steps to go, directly on the code!!!!

 Public classChildthreadhandleractivityextendsActivity {PrivateMyThread Childthread; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_handler); Childthread=NewMyThread ();        Childthread.start (); Handler Childhandler=NewHandler (Childthread.childlooper) {//after that, Childhandler and Childlooper were linked together.              Public voidhandlemessage (Message msg) {};    }; }    Private classMyThreadextendsthread{ PublicLooper Childlooper; @Override Public voidrun () {looper.prepare ();//Create a looper associated with the current threadChildlooper = Looper.mylooper ();//gets the Looper object for the current threadLooper.loop ();//call this method, the message will not be processed        }    }}

Code as above, we still sequential Android three-step strategy, the completion of the sub-thread handler creation, is this created, you can send messages? What thread is the message processed? A series of questions, what to do? Look at the code!!! Running the above code, we found a problem, that is, this code will crash, one will not crash, by looking at the log we see the cause of the crash is a null pointer. Who is empty??? It's our Looper object. Didn't I initialize the Looper object in the Run method of the child thread? Yes, but you know, when you statr a sub-thread, the thread's Run method is executed, but the code in the main thread is still down, and the reason for the null pointer is that when we new Handler (Childthread.childlooper), The Looper object in the Run method has not been initialized. Of course, this situation is random, so it causes the occasional crash.

So what? Can't we create a sub-thread handler??? No!!! No!!! No!!!, you can think of Android long for us to achieve good, Handlerthread class is the key to solve this problem, look at the code!!!

 Public classHandlerthreadactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_handler); TextView TextView=(TextView) Findviewbyid (r.id.tv); Textview.settext ("Handlerthreadactivity.class"); Handlerthread Handlerthread=NewHandlerthread ("Handlerthread");        Handlerthread.start (); Handler Mhandler=NewHandler (Handlerthread.getlooper ()) {@Override Public voidhandlemessage (Message msg) {Super. Handlemessage (msg); LOG.D ("Handlerthreadactivity.class", "uiThread2------" +thread.currentthread ());//Child Threads            }        }; LOG.D ("Handlerthreadactivity.class", "uiThread1------" +thread.currentthread ());//Main ThreadMhandler.sendemptymessage (1); }}

When creating a Handlerthread object, there is a parameter that specifies the name of the thread. The above code no matter how many times the run will not go crashing!!! And this method creates a handler Handlemessage method that runs in a child thread. So we can deal with some time-consuming logic here. In this way we have completed the main thread to notify the child thread, and do the time-consuming logical operation on the child thread.

Below we go to look at the source code, see why use handlerthread can avoid null pointer that?

     PublicLooper Getlooper () {if(!isAlive ()) {            return NULL; }                //If The thread has been started, wait until the Looper have been created.        synchronized( This) {             while(IsAlive () && Mlooper = =NULL) {                Try{wait (); } Catch(Interruptedexception e) {}}} returnMlooper; }

Getlooper method of the Handlerthread class, we see that when we get the current thread Looper object, we will first determine whether the current thread is alive, and then also to determine whether the Looper object is empty, and then return to me Looper object, Otherwise in the waiting state!! Since there is waiting, there is a time to wake up, where is it??? We found that the Handlerthread Run method has the following code:

    @Override    publicvoid  run () {        = process.mytid ();        Looper.prepare ();         synchronized (this) {            = looper.mylooper ();            Notifyall ();        }        Process.setthreadpriority (mpriority);        Onlooperprepared ();        Looper.loop ();         =-1;    }

What does that mean??? When the Handlerthread class is start, the Looper object is initialized and the wait is awakened. So the handlerthread is good to avoid the generation of null pointers. So when you want to create a handler that is not the main thread, we use the Looper object provided by the Handlerthread class.

So far, the first three we talked about the use of handler, working principle, creating sub-thread handler. Next I'll talk about the solution to the memory leak caused by using handler.

Handler series creation sub-thread handler

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.