Figure out the Android interface callback mechanism

Source: Internet
Author: User

This mechanism has not been understood before, and now re-organize the ideas.

First, modeling

I understand that the interface callback is that my class implements a method in an interface Do Something , and then sign up to you, and I'll do something else, and you'll call me back at some trigger time . dosomething the method. Like, I call you to ask a question, you can not think out on the phone, and then said to think back to my phone. So the interface callback mechanism metaphor model is as follows

The first step:

First of all, you and I have to agree, this implementation of the method is how, what name, need to pass in what. Why would you do that? You and I have to arrange a phone call, not a buckle. This is the agreed interface.

We agreed that when you think of the answer to the question back to me, so here the parameter is the answer you think of.

Public interface Contactinterface {public void Callbackbytel (String answer);


Step Two:

I have to call (register) to you and tell you what my problem is. Right.

So there must be a way for me to tell you about the issue (registration).


public void Setcallback (String who,string question,contactinterface callBack) {this.who = who;         SYSTEM.OUT.PRINTLN ("You said:" The person who is currently contacting me is "+who+", the question is "+question");        This.callback =callback;    }

Step Three:

When you think of the answer to the question, call me and tell me the answer, the way I came in.


public void Handlethings () {//If you are thinking of the answer to the question now, take a moment for (int i=0;i<100000;i++) {               if (i = = 0) {                      System.out.println ("You are thinking about the problem ...");}  String answer = "answer is a"; Think of the solution to the problem System.out.println ("You say: think of the answer, ready to call back to" +who+ "tell him the answer"); Callback.callbackbytel (answer); }


OK , The whole mechanism is composed of three elements: I (client), you (server), contract (interface)

My class--

public class Me {public static void main (string[] args) {    me me = new Me (); Me.hasquestion ();  }  private void Hasquestion () {//Now there is a problem to think out the answer, want to ask you to you = new You (); You.setcallback ("Snail", "what is the answer to a question?") ", new Contactinterface () {@Overridepublic void Callbackbytel (String answer) {System.out.println (" I said: Well, OK, I got the answer: "+ answer+ ", thank You");}); You get a call, wake up and start thinking about the problem new Thread (You). Start (); }}

Your Class--

Package Lin.callback.test;public class implements Runnable{private String who; private Contactinterface callback;
   public You () {//TODO auto-generated constructor stub}//Call this method means someone contacted you and registered to you this comes public void Setcallback (String who,strin G Question,contactinterface callBack) {this.who = who; SYSTEM.OUT.PRINTLN ("You said:" The person who is currently contacting me is "+who+", the question is "+question");        This.callback =callback;    }    public void Handlethings () {//If you are thinking of the answer to the question now, take a moment for (int i=0;i<100000;i++) {                if (i = = 0) {              System.out.println ("You are thinking about the problem ...");}  String answer = "answer is a"; Think of the solution to the problem System.out.println ("You say: think of the answer, ready to call back to" +who+ "tell him the answer"); Callback.callbackbytel (answer); }/* (non-javadoc) * @see java.lang.runnable#run () */@Overridepublic void run () {try {thread.sleep (+); handlethings ();} catch (Exception e) {e.printstacktrace ();}}  }

Interface Class--

Public interface Contactinterface {public void Callbackbytel (String answer);


Validation results:



Second, summary

There is no function pointer in Java because java does not have pointers, but it does not mean that it does not use this functionality. In fact, a reference is a function that implements the pointer.

A callback method is a method that is called through a method pointer. If I pass a pointer (address, reference) of this method through a parameter to a method of another class, then this class invokes the method that I passed in the method by invoking the pointer that I have in it.

the whole process was the way I passed in. A address, which you receive, and at some point callback my side of the A method.

because Java There is no way to manipulate the pointer, so it is implemented with an interface.

The Java method callback is a kind of coupling design idea. As an architecture, it must have its own operating environment and provide the user's implementation interface.

The main steps are as follows:

    • Defines the interface Callback, including the callback method Callback ();
    • The service side provides the method of registering, and sets the callback interface method under some conditions;
    • The client provides an implementation method of the interface and registers it with the server to pass in the method address.

This allows the Mcallback interface member of the caller object to invoke the callback () method, when needed, to complete the callback.

Third, Android the callback mechanism in

The callback mechanism is heavily used in Android.

For example, in the activity defines a lot of life cycle of different states to invoke the method, these methods are empty implementations, the system framework to invoke, the user will be called to implement. Or more directly is the key click Implementation method.


Loginbutton.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated Method stub}});

Obviously, Onclicklistener is Android The system is a good interface, and then we write the application is the client, the Android system is the server. The model relationships are as follows:

As can be seen above, the interface (System framework) is provided by the system, the implementation of the interface is user-implemented, so that the interface can be unified to achieve different effects.

System in different states "callback" our implementation class to achieve the classification of interfaces and implementations.

Figure out the Android interface callback mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.