Understanding of Callback Mechanism

This article is reproduced on the blog of Dashen xiaanming( http://blog.csdn.net/xiaanming/article/details/17483273):

In the past, I did not understand what callback was. Every day I heard people say to add a callback method. I thought to myself, what is called callback method? Then I look for it on the internet, and I don't know much about it. Now I know that the so-called callback is to call a method C in class B in class A, and then invoke method D in class B in turn. This method is called callback method. In this way, do you feel a little dizzy? In fact, I just didn't understand it at first, and I read the classical theory. Callback mode:

  • Class A Implementation Interface CallBack callback - Background 1
  • ClassA contains a reference b to class B -- Background 2
  • ClassB has a method f(CallBack callback) with a parameter called back -- background 3
  • Object a of A calls method f(CallBack callback) of B -- Class A calls method C of Class B
  • Then B can call the method of A in f(CallBack callback) - Class B calls a method D of Class A.

Everyone likes to use the example of telephone, well, in order to keep up with the times, I also use this example, I use the example of asynchronous plus callback.

One day Xiao Wang met a very difficult question. The question was "1 + 1 =?". He called Xiao Li and asked him. Xiao Li didn't know at once. He told him that when I finished what I was doing, I would think about the answer. Xiao Wang would not be foolish to hold the phone and wait for Xiao Li's answer. So Xiao Wang said to Xiao Li, I still want to go shopping. If you know the answer, call me and tell him. I hung up and did my own business. An hour later, Xiao Li called Xiao Wang and told him the answer was 2.

  1. /** 
  2.  * This is a callback interface 
  3.  * @author xiaanming 
  4.  * 
  5.  */  
  6. public interface CallBack {  
  7.     /** 
  8.      * This is the function Xiao Li calls when he knows the answer to tell Xiao Wang, that is, the callback function. 
  9.      * @param result That's the answer. 
  10.      */  
  11.     public void solve(String result);  
  12. }  

 

  1. /** 
  2.  * This is Xiao Wang. 
  3.  * @author xiaanming 
  4.  * A CallBack interface called Back is implemented, which is equivalent to ---> Background 1. 
  5.  */  
  6. public class Wang implements CallBack {  
  7.     /** 
  8.      * Reference to Xiaoli Object 
  9.      * Equivalent to - --> Background 2 
  10.      */  
  11.     private Li li;   
  12.   
  13.     /** 
  14.      * Xiao Wang's method of construction, holding Xiao Li's quotation 
  15.      * @param li 
  16.      */  
  17.     public Wang(Li li){  
  18.         this.li = li;  
  19.     }  
  20.       
  21.     /** 
  22.      * Xiao Wang uses this method to ask Xiao Li's questions. 
  23.      * @param question  That's Xiao Wang's question. 1 + 1 = 1? 
  24.      */  
  25.     public void askQuestion(final String question){  
  26.         //One thread is asynchronous.  
  27.         new Thread(new Runnable() {  
  28.             @Override  
  29.             public void run() {  
  30.                 /** 
  31.                  * Xiao Wang calls Xiao Li's method and registers the callback interface here. 
  32.                  * This is equivalent to class A calling method C of B. 
  33.                  */  
  34.                 li.executeMessage(Wang.this, question);   
  35.             }  
  36.         }).start();  
  37.           
  38.         //After asking questions, hang up the phone and do something else. Go to the street.  
  39.         play();  
  40.     }  
  41.   
  42.     public void play(){  
  43.         System.out.println("I'm going shopping.");  
  44.     }  
  45.   
  46.     /** 
  47.      * Xiao Li calls this method after he knows the answer and tells Xiao Wang that it is Xiao Wang's callback method. 
  48.      */  
  49.     @Override  
  50.     public void solve(String result) {  
  51.         System.out.println("Xiao Li told Xiao Wang that the answer was--->" + result);  
  52.     }  
  53.       
  54. }  


 

  1. /** 
  2.  * This is Xiao Li. 
  3.  * @author xiaanming 
  4.  * 
  5.  */  
  6. public class Li {  
  7.     /** 
  8.      * Equivalent to class B, f() --> background 3 with parameter CallBack callBack 
  9.      * @param callBack   
  10.      * @param question  Questions asked by Xiao Wang 
  11.      */  
  12.     public void executeMessage(CallBack callBack, String question){  
  13.         System.out.println("Questions asked by Xiao Wang--->" + question);  
  14.           
  15.         //It takes a long time to simulate Xiao Li's own business.  
  16.         for(int i=0; i<10000;i++){  
  17.               
  18.         }  
  19.           
  20.         /** 
  21.          * Xiao Li finished his own business and thought of the answer is 2. 
  22.          */  
  23.         String result = "The answer is 2";  
  24.           
  25.         /** 
  26.          * So he called Xiao Wang and told him to call Xiao Wang's method. 
  27.          * This is equivalent to class B invoking method D of A in turn. 
  28.          */  
  29.         callBack.solve(result);   
  30.   
  31.           
  32.           
  33.     }  
  34.       
  35. }  


 

  1. /** 
  2.  * Test class 
  3.  * @author xiaanming 
  4.  * 
  5.  */  
  6. public class Test {  
  7.     public static void main(String[]args){  
  8.         /** 
  9.          * new Xiao Li 
  10.          */  
  11.         Li li = new Li();  
  12.   
  13.         /** 
  14.          * new Xiaowang 
  15.          */  
  16.         Wang wang = new Wang(li);  
  17.           
  18.         /** 
  19.          * Xiao Wang asks Xiao Li questions 
  20.          */  
  21.         wang.askQuestion("1 + 1 = ?");  
  22.     }  
  23. }  


Did you get a good idea of the callback mechanism through the example above? It's an asynchronous callback. Let's look at the synchronous callback, onClick () method?

Now let's analyse it. Android View's click method onclick(); we know that onclick() is a callback method. When a user clicks View, this method is executed. Let's use Button as an example.

  1. //This is a callback interface for View  
  2. /** 
  3.  * Interface definition for a callback to be invoked when a view is clicked. 
  4.  */  
  5. public interface OnClickListener {  
  6.     /** 
  7.      * Called when a view has been clicked. 
  8.      * 
  9.      * @param v The view that was clicked. 
  10.      */  
  11.     void onClick(View v);  
  12. }  

  1. package com.example.demoactivity;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.widget.Button;  
  8. import android.widget.Toast;  
  9.   
  10. /** 
  11.  * This is equivalent to Class A 
  12.  * @author xiaanming 
  13.  * Implementation of OnClickListener Interface - > Background 1 
  14.  */  
  15. public class MainActivity extends Activity implements OnClickListener{  
  16.     /** 
  17.      * Class A Contains a reference to Class B - --> Background 2 
  18.      */  
  19.     private Button button;  
  20.   
  21.     @Override  
  22.     public void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.activity_main);  
  25.         button = (Button)findViewById(R.id.button1);  
  26.           
  27.         /** 
  28.          * Class A Call the method of View, and Button extends View - - - - > Class A calls a method of Class B C 
  29.          */  
  30.         button.setOnClickListener(this);  
  31.     }  
  32.   
  33.     /** 
  34.      * The callback function that users call when they click on Button allows you to do what you want to do. 
  35.      * What I did here was to prompt OnClick with Toast 
  36.      */  
  37.     @Override  
  38.     public void onClick(View v) {  
  39.         Toast.makeText(getApplication(), "OnClick", Toast.LENGTH_LONG).show();  
  40.     }  
  41.   
  42. }  

The following is the setOnClickListener method of the View class, which is equivalent to Class B and only pastes out the key code.

  1. /** 
  2.  * This View is equivalent to Class B 
  3.  * @author xiaanming 
  4.  * 
  5.  */  
  6. public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {  
  7.     /** 
  8.      * Listener used to dispatch click events. 
  9.      * This field should be made private, so it is hidden from the SDK. 
  10.      * {@hide} 
  11.      */  
  12.     protected OnClickListener mOnClickListener;  
  13.       
  14.     /** 
  15.      * setOnClickListener()The parameter is OnClickListener interface - --> Background 3 
  16.      * Register a callback to be invoked when this view is clicked. If this view is not 
  17.      * clickable, it becomes clickable. 
  18.      * 
  19.      * @param l The callback that will run 
  20.      * 
  21.      * @see #setClickable(boolean) 
  22.      */  
  23.       
  24.     public void setOnClickListener(OnClickListener l) {  
  25.         if (!isClickable()) {  
  26.             setClickable(true);  
  27.         }  
  28.         mOnClickListener = l;  
  29.     }  
  30.       
  31.       
  32.     /** 
  33.      * Call this view's OnClickListener, if it is defined. 
  34.      * 
  35.      * @return True there was an assigned OnClickListener that was called, false 
  36.      *         otherwise is returned. 
  37.      */  
  38.     public boolean performClick() {  
  39.         sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);  
  40.   
  41.         if (mOnClickListener != null) {  
  42.             playSoundEffect(SoundEffectConstants.CLICK);  
  43.               
  44.             //This is not equivalent to class B calling a method D of class A. This D is the so-called callback method.  
  45.             mOnClickListener.onClick(this);  
  46.             return true;  
  47.         }  
  48.   
  49.         return false;  
  50.     }  
  51. }  

This example is a typical Android callback mechanism. After reading this, do you have a better understanding of the callback mechanism? Thread run() is also a callback method. When the start () method of Thread is executed, it calls back the run() method, and the processing of messages is classical, and so on.


In the next article, I will summarize my understanding of callback mechanism in combination with this article.

Keywords: Android SDK

Added by tsiedsma on Sun, 16 Jun 2019 21:21:18 +0300