English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Deep Understanding of Android Interface Callback Mechanism

At the beginning, I didn't understand this mechanism deeply. Now I am reorganizing my thoughts. In development, interface callback is something we often use.

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

Firstly, let's solve what a callback is:

For example: one day, I called you to ask a question, of course, a difficult one, and you couldn't come up with a solution at that moment. I couldn't just wait there on the phone, so we agreed: wait until you come up with a solution and call me on the phone to notify me. In this way, I hung up the phone and went to do other things. After XX minutes, my phone rang, and you excitedly said that the problem had been solved and should be handled in such and such a way.

 

C does not call b by itself; the purpose of C providing b is to allow S to call it, and C has to provide it. S does not know what b provided by C is, so S will agree on the interface specification (function prototype) of b, and then C will inform S in advance through a function r that it will use the b function (i.e., registration). r is the registration function.

In simple terms: a callback function is a function reserved for system calls, and we often know when the function is called, so let's continue to improve the above diagram.

Looking at this picture, if we think back, we will find that there are all kinds of callback thoughts in life. Many software ideas are actually just a transformation of our way of thinking in actual life.

The first thing we do when we take an exam is to write our student number and name. Here, note that we fill in the student number and name not for ourselves (i.e., the method is not called for ourselves), but for the teacher to record the score (reserved for the system to call in the future), which is actually an application of callback. The teacher provides an interface (input name, student number rules), and we use the interface to register.

After seeing the small example above, you have some understanding of callback, let's go back to the example at the beginning of the article.

That example illustrates the concept of 'asynchronous'.+The programming pattern of 'callback'. Among them, the process of you calling me later to tell me the result is a 'callback' process; my phone number must be told to you in advance, which is the registration of callback function; my phone number should be valid and the phone should be able to receive your call, which is the interface specification that the callback function must meet.

We have a general understanding of the basic process of callback, let's take a look at the basic usage of callback in Android.

Scenario one:

Button button = (Button)this.findViewById(R.id.button);  
button.setOnClickListener(new Button.OnClickListener() {  
  //Callback function  
  @Override  
  public void onClick(View v) {  
   buttonTextView.setText("The button was clicked");  
  }  
});  

The above code adds an event listener to the button, which is one of the most common application scenarios of 'callback'. We do not explicitly call the onClick method. After the user triggers the click event of the button, it will be automatically called by the Android system.

Scenario two:

@Override  
public void onCreate(Bundle savedInstanceState) {  
  super.onCreate(savedInstanceState);  
  // You code...  
}  
@Override  
public void onResume() {  
  super.onResume();  
  // You code...  
}  

The entire lifecycle of Activity is basically where callback functions are in action.

After looking at two commonly used callback methods, let's summarize the basic method of using callbacks in Android. In fact, it's just a translation of our diagram.

--your class--

package lin.callback.test; 
public class You implements Runnable{}} 
  private String who; 
   private ContactInterface callBack;  
   public You() { 
      // TODO Auto-generated constructor stub 
   } 
  //Calling this method means someone has contacted you, and register it here 
   public void setCallBack(String who, String question, ContactInterface callBack) { 
     this.who = who;   
     System.out.println("You said: The person who contacted me is"+who+", the question is"+question); 
     this.callBack = callBack; 
   } 
   public void handleThings() { 
     //Suppose you are thinking about the answer to the problem and need some time 
     for(int i=0;i<100000;i++){  
        if(i == 0){ 
          System.out.println("You are thinking about the problem....."); 
        } 
     } 
     String answer = "The answer is A"; 
     //I've thought of a way to solve the problem 
     System.out.println("You said: I thought of the answer, ready to call back ")+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 question I can't think of the answer, and I want to ask you 
     You you = new You(); 
     you.setCallBack("蜗牛", "What is the answer to the question?", new ContactInterface() { 
      @Override 
      public void callBackByTel(String answer) { 
        System.out.println("I said: Um, okay, I received the answer: ")+answer+"Thank you"); 
      } 
    }); 
    //You receive a phone call, get up and start thinking about the problem 
    new Thread(you).start(); 
   } 
} 

--Interface class (specification)--

public interface ContactInterface { 
  public void callBackByTel(String answer); 
} 

Verification result:

You said: The person who contacted me now is snail, and the question is what is the answer to a certain question?
You are thinking about the problem
You said: Thought of the problem, ready to call back to snail to tell him the answer
I said: Um, okay, I received the answer: The answer is A, thank you

In-depth thinking on callbacks:

The essence of a program is code jumps, no matter synchronous, asynchronous, reflection interface, virtual functions, in essence, they are function calls. Functions we need to call, we need its pointer, different languages through different ways to get this pointer. And the interface we define is actually a function pointer, so that registration process is actually equivalent to that function pointer assignment. Call the self-defined function we define through this function pointer.

That's all for this article. I hope it will be helpful to everyone's learning and also hope everyone will support the Yelling Tutorial more.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like