A detailed explanation of the Java callback mechanism

Source: Internet
Author: User

I. Description

recently, in writing code, it is quite practical to find the Java callback Mechanism. After searching for some information on the internet, we can summarize it according to my own understanding, and I hope that you will help me to correct my mistakes.
Start with a very simple example of Android Development. When we use the Button on the interface, it takes a few steps to increase the Click event Listener for It:
① instantiates a Button object, such as btn_call_back;
②btn_call_back.setonclicklistener (mainactivity.this);
③ This class implements the Onclicklistener interface, overriding the OnClick (view view) method.

The code below, this time we click the button will pop up a paragraph: "click to the callback method button!" as to why this effect can be achieved? is applied to our topic today: Java callback Mechanism.

public class Mainactivity extends appcompatactivity implements View.onclicklistener {    private Button btn_call_back;    @Override    protected void onCreate (Bundle Savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        Btn_call_back = (Button) Findviewbyid (r.id.btn_call_back);        Btn_call_back.setonclicklistener (mainactivity.this);    }    @Override public    void onclick (view view) {        //override onclick method        Toast.maketext (this, "click to callback method button!"), Toast.length_short). Show ();    }}
second, View the source code

2.1 Onclicklistener Interface. The interface is simple and contains only one onclick (view var1) method, and each class that implements the interface must implement the onclick (view var1) method. Does it feel familiar? yes, That's The way we rewrite it in Mainactivity. Keep Looking down.

public interface Onclicklistener {    void OnClick (View var1);}

2.2 Setonclicklistener () Method. This method assigns our incoming mainactivity.this to the Monclicklistener object, what does this do? See how the button is clicked Trigger

/**     * Register A callback to being invoked when the this view is Clicked. If This view was not     * clickable, it becomes clickable.     *     * @param l The callback that would run     *     * @see #setClickable (boolean) */public    void setonclicklist Ener (onclicklistener l) {        if (!isclickable ()) {            setclickable (true);        }        Getlistenerinfo (). Monclicklistener = l;    }

2.3 Click on the trigger method PerformClick (). This method instance listenerinfo the type Object Li mlistenerinfo when li! = null && li.monclicklistener! = NULL when called LI.MONCLICKLISTENER.O Nclick (this), which is the OnClick (view View) method that we rewrote in the mainactivity class.

    /**     * Call this view ' s onclicklistener, if it is Defined.  Performs all normal     * actions associated with clicking:reporting accessibility event, playing     * a sound, etc.
   
    *     * @return True There was a assigned onclicklistener that were called, false     *         otherwise is returned.     *    /public boolean PerformClick () {        final Boolean result;        Final Listenerinfo li = mlistenerinfo;        If (li! = null && li.monclicklistener! = Null) {            playsoundeffect (soundeffectconstants.click);            Li.mOnClickListener.onClick (this);            result = true;        } else {            result = false;        }        Sendaccessibilityevent (accessibilityevent.type_view_clicked);        return result;    }
   
Iii. Summary

3.1 Now we re-comb the callback process, such AS. First mainactivity invokes the Setonclicklistener () method in the View class and passes itself to the Monclicklistener Object. When a click event arrives, the PerformClick () method is triggered, and the OnClick () method is recalled at this Time. This method is the OnClick () method that passes in the mainactivity class. so, The callback mechanism is the class A call method of class b, and Class B in turn calls the Class A method.

3.2 Usage Rules

①a class implements interface CallBack, overriding abstract methods
The ②a class has a reference that can invoke class b, as in the previous example, because the button inherits from the View
The ③b class provides a method fun with parameters that contain the CallBack interface type
The ④a class calls the Class B method fun by reference, so Class B can callback the abstract method of class A override

3.3 Application Scenarios

Callback mechanism is widely used, in my current work as an example, the project in the request network data, version updates applied to the callback Mechanism. Because the main thread can not take the time-consuming operation, it is necessary to open the Sub-thread to obtain the data, here can pass the retrieved data through the callback mechanism to the main thread, version update is the same reason, here is not cumbersome. The above is personal understanding, do not know can leave a message, you are welcome to comment!

A detailed explanation of the 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.