Java callback mechanism

Source: Internet
Author: User
Tags call back

Do not understand what is called the callback, every day listen to people say add a callback method What, my heart think I grass, what is called callback method ah? And then I find it on the Internet Ah find, find a lot is not very clear, now know, called callback: is a class called in Class B of a method C, and then in the Class B in turn called the method in Class A d,d this method called callback method, so that you are not a bit dizzy, in fact, I just started to understand , looked at the other people say the more classic callback method:

    • Class a implements interface callback callback-- background 1
    • Class A contains a reference to Class B b-- background 2
    • Class B has a method with a parameter of CallBack F (CallBack CallBack)-- background 3
    • Object A of a calls B method F (CallBack CallBack)--a class calls a method of Class B
    • Then B can call a method in the F (CallBack CallBack) method--b class calls a method of Class D

We all like to use the phone example, well, in order to keep up with the times, I also use this example, I use this example of asynchronous plus callback

One day Xiao Wang encountered a difficult problem, the question is "1 + 1 =?", on the phone to ask Xiao Li, Xiao Li suddenly did not know, and Xiao Wang said, and so I finish the things on hand, to think about the answer, Xiao Wang will not be silly to take the phone to wait for Xiao Li's answer, so Xiao Wang said to Xiao Li, I have to go shopping, You know the answer to call me to tell me, so hang up the phone, do their own things, after one hours, Xiao Li hit the small Wang's phone, told him the answer is 2

/**   * This is a callback interface   @author  xiaanming  *  * */public   Interface CallBack {      /**      * This is the function that Xiao Li will call when he knows the answer, that is,      the callback function @param result is the      answer */       Public void solve (String result);  }  
/*** This is Xiao Wang *@authorXiaanming * Implements a callback interface callback equivalent to-----> background*/   Public classWangImplementsCallBack {/*** Reference to Xiao Li Object * equivalent to-----> background two*/      PrivateLi Li; /*** The construction method of Xiao Wang, holding the citation of Xiao Li@paramLi*/       PublicWang (Li Li) { This. Li =Li; }            /*** Xiao Wang is going to ask Xiao Li's question through this method.@paramquestion is the question that Xiao Wang wants to ask, 1 + 1 =? */       Public voidAskquestion (FinalString question) {          //here a thread is asynchronous,        NewThread (NewRunnable () {@Override Public voidrun () {/*** Xiao Wang calls the method of the small Lee, register the callback interface here * This is equivalent to the Class A call B method C*/li.executemessage (Wang. This, question);                    }}). Start (); //The net asks the question to hang up the telephone to do other things, exaggeration street.Play (); }         Public voidPlay () {System.out.println ("I'm going to go shopping."); }        /*** Xiao Li know the answer after calling this method to tell Xiao Wang, is the so-called Xiao Wang's callback method*/@Override Public voidsolve (String result) {System.out.println (Xiao Li told Xiao Wang that the answer is---> "+result); }        } 
/*** This is Xiao Li *@authorxiaanming **/   Public classLi {/*** equivalent to Class B with parameters of callback callback F ()----> Background three *@paramCallBack *@paramquestion Little Wang asked the question*/       Public voidexecutemessage (CallBack CallBack, String question) {System.out.println ("Little Wang asked the question--->" +question); //It takes a long time to simulate Xiao Li's own affairs.         for(inti=0; i<10000;i++){                        }                    /*** When Xiao Li finishes his own business, he thinks the answer is 2.*/String Result= "Answer is 2"; /**so I called Xiao Wang and called the King's method * This is equivalent to Class B, which in turn calls a method D*/callback.solve (Result); }        }  
/*** Test class *@authorxiaanming **/   Public classTest { Public Static voidMain (String[]args) {/*** New A little Lee*/Li Li=NewLi (); /*** New A little King **/Wang Wang=NewWang (LI); /*** Xiao Wang asked Xiao Li's question*/Wang.askquestion ("1 + 1 =?"); }  }  

By the above example, do you almost understand the callback mechanism, which is an asynchronous callback, let's look at the synchronous callback, the OnClick () method

Now to analyze and analyze the click method of the Android View onclick (); We know that the onclick () is a callback method, and when the user clicks on the view to execute the method, we use the button to give an example.

// This is a callback  interface for view /**   * Interface definition for a callback to being invoked when a view is clicked.   */   Public Interface Onclicklistener {      /**      * Called when a view has been clicked.      *      @param  v The view that is clicked.       */      void OnClick (View v);  }  
 Packagecom.example.demoactivity; Importandroid.app.Activity; ImportAndroid.os.Bundle; ImportAndroid.view.View; ImportAndroid.view.View.OnClickListener; ImportAndroid.widget.Button; ImportAndroid.widget.Toast; /*** This is equivalent to class A *@authorxiaanming * Implements the Onclicklistener interface----> Background one*/   Public classMainactivityextendsActivityImplementsonclicklistener{/*** Class A contains reference to class B-----> Background two*/      Privatebutton button; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);          Setcontentview (R.layout.activity_main); Button=(Button) Findviewbyid (R.id.button1); /*** Class A calls the method of view, and button extends view-----The >a class calls some method of Class B*/Button.setonclicklistener ( This); }        /*** The callback function called when the user clicks the button, you can do what you want to do * Here I do is to use toast hint onclick*/@Override Public voidOnClick (View v) {toast.maketext (Getapplication (),"OnClick", Toast.length_long). Show (); }    }  

The following is the Setonclicklistener method of the view class, which is equivalent to Class B, and only the key code is posted.

/*** This view is equivalent to Class B *@authorxiaanming **/   Public classViewImplementsDrawable.callback, Keyevent.callback, Accessibilityeventsource {/*** Listener used to dispatch click events.      * This field should was made private, so it's hidden from the SDK. * {@hide}*/      protectedOnclicklistener Monclicklistener; /*** Setonclicklistener () parameter is Onclicklistener interface------> Background three * Register a callback to being invoked when the this view is clicked.      If This view was not * clickable, it becomes clickable. *      * @paramL The callback that'll run * *@see#setClickable (Boolean)*/             Public voidSetonclicklistener (Onclicklistener l) {if(!isclickable ()) {setclickable (true); } Monclicklistener=l; }                  /*** Call this view ' s Onclicklistener, if it is defined. *      * @returnTrue There was a assigned onclicklistener that were called, false * otherwise is returned. */       Public BooleanPerformClick () {sendaccessibilityevent (accessibilityevent.type_view_clicked); if(Monclicklistener! =NULL) {playsoundeffect (Soundeffectconstants.click); //This is not the equivalent of Class B calls a Class A method D, this is the so-called callback methodMonclicklistener.onclick ( This); return true; }            return false; }  }  

This example is the typical Android callback mechanism, after reading this you do not further understand the callback mechanism? Thread run () is also a callback method, when the start () method that executes the thread will call back to the Run () method, and the processing message is more classic and so on

from:http://blog.csdn.net/xiaanming/article/details/8703708/

 Public classTestcallbackImplementsCallback {Static intval = 0;  Public Static voidMain (string[] args) {NewCb (Newtestcallback ());    System.out.println (Val); } @Override Public voidSetValue (intval) {         This. val =Val; }}classCb {Private intval = 10;  PublicCB (Callback CB) {Cb.setvalue (val); }}InterfaceCallback {voidSetValue (intval);}

Java 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.