Android principle-callback mechanism and android callback mechanism
Android callback mechanism
Callback functions can separate callers from callers. Callers do not care who are called. callers only need to know the called functions with specific prototypes and restrictions.
1. Define a callback function;
2. The party that provides function implementation submits the callback function interface Instantiation to the caller during initialization;
3. When a specific event or condition occurs, the caller uses the interface to call the callback function to process the event.
I have seen a better description:Class A calls A method C of Class B, and Class B calls the method D of Class A in turn. Class D is called the callback method.
First, we will reference a classic example in the Android source code:
// Interface Class, Class B Implementation interface, Class A call interface public interface OnClickListener {void onClick (View v );}
// Equivalent to class A public class MainActivity extends Activity implements OnClickListener {private Button button; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); button = (Button) findViewById (R. id. button1); // Class A instantiation interface button. setOnClickListener (this);} @ Override public void onClick (View v) {// callback function }}
// Equivalent to class B public class View implements Drawable. callback, KeyEvent. callback, AccessibilityEventSource {// interface instance protected OnClickListener mOnClickListener; // interface instantiation public void setOnClickListener (OnClickListener l) {if (! IsClickable () {setClickable (true);} mOnClickListener = l;} public boolean complete mclick () {if (mOnClickListener! = Null) {// Class B calls the implementation method of Class A mOnClickListener. onClick (this); return true ;}return false ;}}
The above example is clearly written. Here I use markdown to make a picture:
Created with Rapha rjl 2.1.2 Class Class Class B Class B SetCallback (this) Implements Callback OnCallback () Interface Callback {} Callback callback OnCallback ()