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