Android callback function 1: Basic Concepts: android callback function
1. Concepts
Client program C calls A function A in service program S, and then S calls A function B in C at some time. For C, this B is called A callback function.
Generally, C does not call B by itself. C provides B for S to call it, and C has to provide it.
Because S does not know who the B surname provided by C is, S will agree with the interface specification (function prototype) of B ), then C tells S to use the B function through a function R of S in advance. This process is called the registration of the callback function, and R is called the registration function.
2. Example
One day, I called to ask you a question. Of course it was a problem. ^ _ ^. You couldn't figure out a solution at the moment, and I couldn't wait there with a phone. So we agreed: after you have come up with a solution, you can call me to notify me. In this way, I will stop calling to handle other things. After XX minutes, my cell phone rang, and you said with high enthusiasm that the problem had been fixed, so you should handle it like this. The story ends here. This example illustrates the "Asynchronous + callback" programming mode. When you call a mobile phone to tell me that the result is a "Callback" process. My mobile phone number must be told before. This is the registration callback function; my mobile phone number should be valid and the mobile phone can receive your call. This is the callback function that must comply with the interface specifications.
3. An Android instance
A. Define the interface
Public interface OnClickListener {
Public void OnClick (Button B );
}
B. Define the Button
Public class Button {
OnClickListener listener;
Public void click (){
Listener. OnClick (this );
}
Public void setOnClickListener (OnClickListener listener ){
This. listener = listener;
}
}
C. Assign the OnClickListener interface object to the interface member of the Button.
Public class Activity {
Button button = new Button ();
Button. setOnClickListener (new OnClickListener (){
@ Override
Public void OnClick (Button B ){
System. out. println ("clicked ");
}
});
Button. click (); // user click, System call button. click ();
}
}
4. Application Instances
Android callback function 2: Application Instance