First, preface
This week, a friend who was in the early days of the development asked me what the callback was, and read a lot of the callback function on the Internet, but the more I looked at it, the more messy. Although the stem of the callback function is not new, it is written in the form of a record.
If you know something, you don't have to look at it.
Second, the concept
Conceptually, here is the explanation of Baidu Encyclopedia, as follows:
The callback function is a function Pointers the function that is called. If you pass the pointer (address) of the function as an argument to another function, when the pointer is used to invoke the function it points to, we say this is a callback function. The callback function is not called directly by the implementing party of the function, but is invoked by another party when a particular event or condition occurs, and is used to respond to the event or condition.
The definition of Baidu Encyclopedia is the above, it refers to the concept of function pointers, function pointers are generally the proper nouns of C + +. Java also has this concept, but we call it reference, fade the concept of function pointers, the use is more simple.
The definition of this concept seems to be a bit around and not easy to understand. There are many descriptions of callback functions on the Internet, for example, Class A calls the Class B method B1,b class and calls the Class A method A1. Such a statement, in fact, is also very confused.
Therefore, a hierarchical explanation of the callback function is given below.
Iii. elements
According to the concept, we know that the call flow of a callback function requires the following three elements and gives them a name, respectively:
1, callback function itself-callback function;
2, the callback function as a parameter passed in the function--intermediate function;
3, caller (call function)--call function.
According to the above naming, the callback function flow is:
(1) The reference to the callback function is passed to the intermediate function (this can also be called the Registration/subscription of the callback function).
(2) Call the function to call the intermediate function, triggering the event of the callback function.
Plain text description may not feel, here we introduce a very simple example to describe this process:
First, you need a callback function:
Package Com.callback;public class Callback {public void call () {System.out.println ("I am a callback function, when I am printed out, the callback function is triggered");}}
Second, one more intermediate function:
Package Com.callback;public class Middle {//parameter is a reference to the class where the callback function is located public void mid (callback callback) {//Trigger callback function Callback.call ();}}
Finally, the function is called:
Package Com.callback;public class Main {/** * @param args */public static void Main (string[] args) { middle m=new Midd Le (); The callback function registers, passing the Callback reference to the intermediate function M.mid (new Callback ());} }
Run it and you can see the results:
I am a callback function, and when I am printed out, the callback function is triggered.
The above is a simple example, in this case, the simplest way to imitate the callback function call process. However, we do not or seldom use it in our daily life, because the example does not show a good function of the callback.
What is the function of the callback function? On the Baidu Encyclopedia there is a description of their meaning:
1, because the caller can be separated from the callee, so the caller does not care who is the callee. It only needs to know that there is a called function with a specific prototype and constraints .
2, callback can be used to notify the mechanism.
3. This design allows the underlying code to invoke subroutines defined at the top level.
Simply put, it can be used for decoupling, notification, and others.
To fully illustrate the function of the callback function, let's do an extension on the original example and introduce an interface. The extension is also the above example, the introduction of interfaces:
New interface:
Package Com.callback;public interface Callbackinterface {public void Call ();}
The original callback function to implement the above interface:
Package Com.callback;public class callback implements Callbackinterface{public void Call () {//TODO auto-generated method StubSystem.out.println ("I am a callback function, when I am printed out, the callback function is triggered");}}
The parameters of the intermediate function, make the following modifications (Modify to interface):
Package Com.callback;public class Middle {//parameter is a reference to the class in which the callback function is located public void mid (Callbackinterface callback) {// Trigger callback function Callback.call ();}}
Finally, the function is called:
Package Com.callback;public class Main {/** * @param args */public static void Main (string[] args) { middle m=new Midd Le (); callback function Registration callbackinterface ifsimpl=new Callback (); M.mid (Ifsimpl);}}
Comparing two examples, in the following example, the interface is introduced to realize the decoupling of the calling function, the intermediate function and the callback function. The underlying function calls to the high-level function. Notification mechanism.
Iv. callback function as a parameter passed in method
This is a small detail, the designer can follow the three ways of dependency injection, to implement the parameters of the callback function passed in.
1, in the constructor of the incoming;
2, by the set method of incoming;
3, directly into the function (interface) as a parameter;
The third way is in the example.
Here, the introduction of the callback function is basically over. However, there are still some gaps between the two examples above and our actual exposure.
After reading the above example, the callback has a relatively deep understanding. Now, it is possible to integrate theory with practice.
also cite a lot of scenes commonly used in a day: button click events in Android (this is also the most widely used callback function).
Five, Andriod button click event Simulation comparison
1, a new Android project, we do a real button click event, as follows:
Original button btn= (button) Findviewbyid (R.ID.BTN); Btn.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated method StubSystem.out.println ("button was clicked-Original");});
2, again according to our own analysis, do a button click on the callback function event:
Also first is a callback function:
Package Com.example.callbackandroid;public interface Myonclicklistener {//callback function public void OnClick ();}
Intermediate function:
Package Com.example.callbackandroid;public class MyButton {private Myonclicklistener listener;//callback function Registration/subscription/Registration Public void Setonclicklistener (Myonclicklistener listener) {This.listener=listener;} public void Doonclick () {Listener.onclick ();}}
Call Function:
Analogue MyButton mbutton=new MyButton (); Mbutton.setonclicklistener (New Myonclicklistener () {@Overridepublic void OnClick () {//TODO auto-generated method StubSystem.out.println ("button was clicked-Original");}); Mbutton.doonclick ();
In contrast to the original Android click events and our simulated Android Click events, we found a little difference: the original Android Click did not need to call the Doonclick event, no call function??
In fact, the original Android Click event has a calling function, but it doesn't have to be written here. If you have seen the Android onclick event (event distribution) source friend, will find: In the source code, when the Android system detects the action_up operation of the view, will call PerformClick () This function, and the contents of this function is as follows:
public boolean PerformClick () { sendaccessibilityevent (accessibilityevent.type_view_clicked); if (Monclicklistener! = null) { playsoundeffect (soundeffectconstants.click); Monclicklistener.onclick (this); return true; } return false;}
It's called the function, which is implemented here. As long as Monclicklistener is not NULL (this is assigned by our Setonclicklistener), the onclick is called.
Therefore, it is the same as the analog click Principle.
Here, the analysis of the callback function is over.
The next paragraph, is mainly a concept of collation.
six, callback function and synchronous, asynchronous
When you really use callback functions, we often get into contact with asynchronous callbacks, asynchronous calls, and synchronous invocations of these words. Here is a simple concept to avoid confusion, as the end.
Synchronous invocation:
This is the most frequent use of a call method, which is a blocking call, such as you call a method, wait for the method to return, or to complete the execution.
Asynchronous invocation:
This is also used in Android frequently, non-blocking calls, such as you call a method, do not wait for this method to return, that is, to perform other operations down.
Asynchronous callbacks:
This is the form of an asynchronous + callback.
Java (Android) callback functions in a detailed