Android Thread Looper

Source: Internet
Author: User

have been dedicated to the use of handler and message, this chapter to understand the handler internal use, this chapter mainly discusses looper in the processing of handler message mechanism plays an important role, We know that we have a message in the child thread to the main thread through the SendMessage () method, handler processing the message is through the Handmessage () method, the internal message passing mechanism, let us explore together.

In order to facilitate everyone's understanding, here I use an example of daily life to introduce you to the handler, Looper processing Details: example is that we have a meeting, to go to the toilet.

  

Seeing the above example, I think we must have a good understanding of looper.

Implement the Handler object in the self-built thread class:

 Public classMainactivityextendsActivity {PrivateHandler Firsthandler =NewHandler () { Public voidhandlemessage (android.os.Message msg) {System.out.println ("UI-------;:" +Thread.CurrentThread ());    };        }; classMythreadextendsthread{PrivateHandler Handler; @Override Public voidrun () {looper.prepare ();//Create a Looper objectHandler =NewHandler () {@Override Public voidhandlemessage (Message msg) {System.out.println ("Child Thread:" +Thread.CurrentThread ());            }            }; Looper.loop ();//This method of cyclic processing                    }    }; PrivateMythread thread; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main); Thread=NewMythread ();        Thread.Start (); Try{Thread.Sleep (3000); } Catch(interruptedexception e) {e.printstacktrace (); } thread.handler.sendEmptyMessage (1);//processing in a child threadFirsthandler.sendemptymessage (1);//processing in the main thread} @Override Public BooleanOncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true; }}

Logcat Information:

  

Android Thread Looper

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.