About Android Siege Lion Handler

Source: Internet
Author: User

What is handler? Handler is a set of mechanisms that Android provides to update the UI and a set of message handling mechanisms through which messages can be sent or processed. The methods of all activity lifecycle callbacks (such as OnCreate (), Ondestory (), and so on) are sent through the handler mechanism, and then the corresponding branch is processed according to different messages (message). For example, send a message to the Framework informing you that you need to call the OnCreate () or Ondestory () method. In fact, in the Framework, the interaction of activity is mostly handled by AMS (activity Manager Service). One of the core classes of the entire application is activity thread,activity Thread is receiving activity Manager through the handler mechanism The service sends messages about the management of the activity lifecycle (such as startup). Why use handler? Android is designed to encapsulate a set of message creation, delivery, processing mechanism, if you do not follow such a mechanism, there is no way to update the UI information, and will throw exception information. Such a mechanism would include the handler mechanism.

1. When we create a handler, it binds to the default thread, and there is a MessageQueue (message queue) in the default thread. 2. Handler two uses: (1) periodically sends a messages or Runnables object; (2) The action of an action can be processed and executed in one thread. 3. The main thread runs a message queue and manages some top-level application objects (top-level application objects), including activity, broadcast receiver, and so on, which are created by default in the activity Thread (which is what we often call the UI thread or the main thread).


Handler example to implement the picture carousel. Code Implementation 1. Define a ImageView control in the main layout. 2. Create and initialize the ImageView in mainactivity, define an array of images images and arrays subscript index, create a handler object. 3. Create an inner class myrunnable implement the Runnable interface, overriding the Run () method: public   void Run () {       index++;       index = index%3; Picture carousel (generally implemented by Viewpager)       Imageview.setimageresource (Images[index]);       Handler.postdelayed (myrunnable,1000); Change the picture}4 every second   . Call handler in the Oncreste () method, which is called handler in the main thread:   handler.postdelayed (myrunnable,1000);
1  Public classMainactivityextendsactionbaractivity {2      PrivateHandler handler1 =NewHandler ();3     PrivateHandler Handler2 =NewHandler (NewCallback () {4 5 @Override6          Public Booleanhandlemessage (Message msg) {7             //TODO auto-generated Method Stub8Toast.maketext (Getapplicationcontext (), "1", 1). Show ();9             return false;//if set to True, do not execute behindTen         } One     }) { A  -          Public voidhandlemessage (Message msg) { -             //TODO auto-generated Method Stub theToast.maketext (Getapplicationcontext (), "2", 1). Show (); -         } -  -     }; +      -      +     PrivateHandler Handler3 =NewHandler () { A          Public voidhandlemessage (android.os.Message msg) { at             //textview.settext ("+msg.arg1+"-"+msg.arg2"); -Textview.settext ("" +msg.obj); -         }; -     }; -      -      in     PrivateTextView TextView; -     PrivateImageView ImageView; to     Private intImage[] ={r.drawable.a, r.drawable.b, r.drawable.c}; +     Private intindex; -  the @Override *     protected voidonCreate (Bundle savedinstancestate) { $         Super. OnCreate (savedinstancestate);Panax Notoginseng Setcontentview (r.layout.fragment_main); -TextView =(TextView) Findviewbyid (R.id.textview); theImageView =(ImageView) Findviewbyid (r.id.imageview1); +         NewThread () { A              Public voidrun () { the                 Try { +Thread.Sleep (2000); -                     //(1) $                     //message Message=new message (); $                     //message.arg1=88; -                     //message.arg2=100; -  the                     //(2) -Message message =handler3.obtainmessage ();Wuyi  thePerson person =NewPerson (); -Person.age = 23; WuPerson.name = "Zy"; -Message.obj =Person ; About                     //handler.sendmessage (message);//(1) $Message.sendtotarget ();//(2) -  -}Catch(interruptedexception e) { -                     //TODO auto-generated Catch block A e.printstacktrace (); +                 } the             }; - }.start (); $  the         /* the * New Thread () { the * public void Run () { the * try {thread.sleep (+); - * Handler.post (New Runnable () { in          *  the * @Override the * public void Run () { About *//TODO auto-generated method stub the * Textview.settext ("update Thread");} }); the          *  the *} catch (Interruptedexception e) {//TODO auto-generated catch block + * E.printstacktrace ();} }; }.start (); -          */ the BayiHandler1.postdelayed (myrunnable, 1000);//1000: Change once in a second the  the     } -  -Myrunnable myrunnable =Newmyrunnable (); the //Picture Loop Playback the     classMyrunnableImplementsRunnable { the  the @Override -          Public voidrun () { the             //TODO auto-generated Method Stub theindex++; theindex = index% 3;94 Imageview.setimageresource (Image[index]); theHandler1.postdelayed (myrunnable, 1000); the         } the     }98  About     classPerson { -          Public intAge ;101          PublicString name;102 103 @Override104          PublicString toString () { the             //TODO auto-generated Method Stub106             return"Name=" + name + "age=" +Age ;107         }108     }109  the      Public voidClick (View view) {111 handler1.removecallbacks (myrunnable); theHandler2.sendemptymessage (1);113     } the  the}

Why is Android designed to update the UI only through the handler mechanism? The most fundamental goal is to solve the problem of multithreading concurrency. 1. What would happen if there were multiple threads in an activity that were updating the UI and had no lock mechanism? -Update interface clutter. 2. What will happen if you lock up the operation of the update UI? -Performance degradation. It is the above considerations, Android provides us with a set of updating the UI mechanism, we only need to follow such a mechanism, we do not have to care about multithreading (concurrency) problem, all the update UI operations are in the main thread of the message queue to "poll" processing. What is the principle of handler? Interview Classic question: Looper, Handler, Message (or MessageQueue) the relationship between the three? Handler encapsulates the sending of messages (mainly to whom the message is sent (by default, handler itself) and when it is sent). Looper:1. The internal contains a message queue MessageQueue, and all Handler messages are routed to (join) this message queue. 2.looper.looper method, is a dead loop, constantly get the message from MessageQueue, if there is a message to process the message, no message is blocked. Second, Messagequeuemessagequeue is a message queue that can add messages and process messages. Third, Handler is also very simple, the interior will be associated with the Looper, that is, in the Handler can find Looper inside, found the Looper also found a Message. Sending a message in Handler is actually sending a message to the MessageQueue queue. Summary: Handler is responsible for sending messages, Looper is responsible for receiving Handler sent messages, and directly to the message back to Handler itself, MessageQueue is a container to store messages.




About Android Siege Lion Handler

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.