Deep understanding of Android's interface callback mechanism _android

Source: Internet
Author: User
Tags call back event listener function prototype reflection

Just beginning to learn about this mechanism is not deep enough, now rearrange the idea. In development, interface callbacks are often used by us.

The meaning of an interface callback is that it does not execute immediately after registration, and at a certain time it triggers execution.

First fix what is a callback:

For example: One day, I call you to ask questions, of course, is a difficult problem, you can't think of a solution, I can not take the phone there silly, so we agreed: when you think of a way to call me, so I hung up the phone to do other things to go. After xx minutes, my mobile phone rang, you cheerfully said that the problem has been done, should be so dealt with.

C does not call B,c itself the purpose of providing B is to let s invoke it, and C has to provide it. s does not know what B is provided by C, so S will agree to B's interface specification (function prototype), and then a function of C in advance through s to tell S oneself will use B function (that is, registration). R is the registration function.

In a nutshell: A callback function is a function reserved for a system call, and we often know when the function is invoked, so we continue to refine the image above.

Looking at this picture, in fact, we think back, we will find that life is full of callback this thought exists. Many of the ideas of software are just a transformation of the way we think in real life.

What is the first thing we do in our daily exams? Yes, it's the school number and the name. Notice here, we fill in the school number and the name is not for ourselves to see (that is, the method is not to call itself), but for the teacher to register scores to see (for the system to future calls), which is actually a callback application. The teacher provides the interface (enter name, learn number rule), we use interface to register.

See the small example above, we have some understanding of the callback, we go back to the beginning of the article example.

That example illustrates the programming pattern of "asynchronous + callback". In which, you later call me the result is a "callback" process; My phone number must have told you before, this is the registration callback function; My cell phone number should be valid and the phone can receive your call, which is the callback function must conform to the interface specification.

We already know the basics of the callback, and let's look at the basic use of the callback in Android.

Scene One:

Button button = (button) This.findviewbyid (R.id.button);  
Button.setonclicklistener (Newbutton.onclicklistener () {  
  //callback function  
  @override  
  publicvoidonclick (View v) {  
   buttontextview.settext ("button clicked");  
  }  
);  

The above code adds an event listener to the button, which is actually one of the most common scenarios for "callback." We do not explicitly invoke the OnClick method ourselves. After the user triggers the Click event for the button, it is automatically invoked by the Android system.

Scene Two:

@Override  
publicvoidoncreate (bundlesaveinstancestate) {  
  super.oncreate (saveinstancestate);  
  You code ...  
}  
@Override  
Publicvoidonresume () {  
  super.onresume ();  
  You code ...  
}  

The whole lifecycle of an activity basically says that the callback function works.

Looking at two of the callback methods we use a lot, let's summarize the basics of Android's use of callbacks. In fact, we just translated the picture.

--Your class--

Package lin.callback.test; 
   public class for implements runnable{private String who;  
   Private Contactinterface CallBack; Public You () {//TODO auto-generated constructor stub}//Call this method means someone contacted you, registered to you here to public void setcal   
     Lback (String who,string question,contactinterface callBack) {this.who = who; 
     SYSTEM.OUT.PRINTLN ("You said:" The person who contacted me at present is "+who+", the problem is "+question"); 
   This.callback =callback;  public void Handlethings () {//If you are now thinking the answer to the question, you need a little time for (int i=0;i<100000;i++) {if (i = = 
        0) {System.out.println ("You are thinking about the problem ..."); 
     } String answer = "answer is a"; 
     The way to think of a problem System.out.println ("You say: think of the answer, ready to call back to" +who+ "tell him the answer"); 
   Callback.callbackbytel (answer); 
      }/* (non-javadoc) * @see java.lang.runnable#run () * * * @Override public void Run () {try { 
      Thread.Sleep (1000); 
    Handlethings (); catch (Exception e) {E.PRintstacktrace (); 
 } 
  }  
}

--My class--

public class Me {public 
  
   static void Main (string[] args) {  
      
     me me = new Me (); 
     Me.hasquestion (); 
      
   } 
    
   private void Hasquestion () { 
     //Now there is a problem can not think out the answer, would like to ask you for your 
     = new You (); 
     You.setcallback ("snail", "what is the answer to a question?") ", new Contactinterface () { 
        
      @Override public 
      void Callbackbytel (String answer) { 
        System.out.println (" I said: Well, well, I got the answer: "+answer+", thank You "); 
    You get a call and start thinking about the problem 
    new Thread (You). Start (); 
 

--Interface Class (specification)--

Public interface Contactinterface {public 
    
  void Callbackbytel (String answer); 
    
} 

Validation results:

You said: The current contact me is a snail, the question is what is the answer to a question?
You're thinking.
You said: Think of the problem, ready to call back to the snail to tell him the answer
I said, "Well, well, I got the answer:" A, thank you.

A deep reflection on the callback:

The nature of the program is the code jump, regardless of synchronous asynchronous reflection interface virtual function, is essentially a function call. function we want to call it, we need its pointers, different languages to get this pointer in different ways. And the interface we define is actually a function pointer, then that registration process is actually the equivalent of assigning to that function pointer. This function pointer is used to invoke our defined implementation function.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.