A classic example allows you to thoroughly understand the Java callback mechanism

Source: Internet
Author: User

In the past, I didn't understand what callback is. I heard people add a callback method every day. I thought about it. What is the callback method? Then you can find it on the Internet, find it, and find it many times. Now you know, the so-called callback: that is, Class A calls a method C in Class B, then Class B calls the method D in Class A in turn. The method D is called the callback method. In this way, do you feel dizzy? In fact, I didn't understand it at the beginning, I have read the classic callback method:

  • Class A implements the callback --Background 1
  • Class A contains a reference of Class B --Background 2
  • Class B has a callback method F (callback )--Background 3
  • Object A of A calls B's method F (callback) -- class A calls a method C of Class B
  • Then, B can call the method A in the F (callback) Method -- class B calls a method D in Class.

We all like the example of making calls. Well, to keep up with the times, I also use this example. In this example, I use Asynchronous and callback.

One day Mr. Smith encountered a very difficult problem: "1 + 1 = ?", I called Xiao Li and asked Xiao Li if he didn't know it at all. He told Xiao Wang that when I finish my work, I should think about the answer, john won't wait for Xiao Li's answer by phone, so he said to Xiao Li, "I want to go shopping. If you know the answer, I will call you to tell me, after an hour, Mr. Li called Mr. Wang and told him the answer was 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 to tell Xiao Wang, that is, the callback function * @ Param result is the answer */Public void solve (string result );}

 

/*** This is Xiao Wang * @ author xiaanming * implemented a callback interface callback, it is equivalent to -----> Background 1 */public class Wang implements callback {/*** reference of the small Li object * equivalent to -----> background 2 */private Li; /*** the constructor of Tom, holding the reference of Tom * @ Param li */Public Wang (Li) {This. li = Li;}/*** Xiao Wang asked Xiao Li's question through this method * @ Param question is the question that Xiao Wang asked, 1 + 1 =? */Public void askquestion (final string question) {// here, a thread is asynchronous, and new thread (New runnable () {@ overridepublic void run () {/*** Mr. Smith calls Xiao Li's method. Registering the callback interface here * is equivalent to Class A calling method C */li.exe cutemessage (Wang. this, Question );}}). start (); // after the small network asks a question, call the phone to do other things, and play ();} public void play () {system. out. println ("I'm going to go shopping");}/*** Xiao Li calls this method to tell Xiao Wang after knowing the answer, is the so-called callback Method */@ overridepublic void solve (string result) {system. out. println ("the answer Mr. Li told Mr. Wang is --->" + result );}}

 

/*** This is Xiao Li * @ author xiaanming **/public class Li {/*** equivalent to F () of Class B with callback Parameters () ----> background 3 * @ Param callback * @ Param question Q & A */Public void executemessage (callback, string question) {system. out. println ("question asked by Mr. Wang --->" + question); // it takes a long time to simulate Mr. Li's own tasks for (INT I = 0; I <10000; I ++) {}/*** after Xiao Li finished his work, he thought of the answer: 2 */string result = "The answer is 2";/*** then he called to tell Xiao Wang, call the Method * in the sub-King. This is equivalent to calling the method D */callback of Class B. solve (result );}}

 

/*** Test class ** @ author xiaanming **/public class test {public static void main (string [] ARGs) {/*** New: Xiao Li */Li = new Li ();/*** New: Xiao Wang */Wang = new Wang (LI ); /*** Xiao Wang asked Xiao Li a question */Wang. askquestion ("1 + 1 =? ");}}

Through the example above, do you almost understand the callback mechanism? The above is an asynchronous callback. Let's look at the synchronous callback, onclick () method.

Now let's analyze and analyze the onclick () method of the android view. We know that onclick () is a callback method. When the user clicks view, this method is executed. We use the button as an example.

// This is a callback interface of View/*** interface definition for a callback to be invoked when a view is clicked. */public interface onclicklistener {/*** called when a view has been clicked. ** @ Param v the view that was clicked. */void onclick (view V );}

Package COM. example. demoactivity; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. toast; /*** this is equivalent to Class A * @ author xiaanming * implementing the onclicklistener interface ----> Background 1 */public class mainactivity extends activity implements onclicklistener {/*** Class A contains class reference of B -----> background 2 */private button; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); button = (button) findviewbyid (R. id. button1);/*** Class A calls the view method, while the button extends view -----> Class A calls a method C */button of Class B. setonclicklistener (this);}/*** the callback function called when the user clicks the button, you can do what you want to do * Here I am using toast to prompt onclick */@ overridepublic void onclick (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. Only key code is posted.

/*** This view is equivalent to Class B * @ author xiaanming **/Public Class View implements drawable. callback, keyevent. callback, accessibilityeventsource {/*** listener used to dispatch click events. * This field shoshould be made private, so it is den from the SDK. * {@ hide} */protected onclicklistener monclicklistener;/*** the setonclicklistener () parameter is the onclicklistener interface ------> background 3 * register a callback to be invoked W Setting this view is clicked. if this view is not * clickable, it becomes clickable. ** @ Param l the callback that will run ** @ see # setclickable (Boolean) */Public void setonclicklistener (onclicklistener L) {If (! Isclickable () {setclickable (true);} monclicklistener = L;}/*** call this view's onclicklistener, if it is defined. ** @ return true there was an assigned onclicklistener that was called, false * otherwise is returned. */Public Boolean merge mclick () {sendaccessibilityevent (accessibilityevent. type_view_clicked); If (monclicklistener! = NULL) {playsoundeffect (soundeffectconstants. click); // This is not equivalent to calling a method D of Class A in Class B. This D is the so-called callback method. onclick (this); Return true;} return false ;}}

This example is a typical callback mechanism of Android. Have you understood the callback mechanism further? The thread run () is also a callback method. When the thread's start () method is executed, the run () method is called back, and the message processing is classic.

This is what the younger brother understands about the callback mechanism. Leave a message if you do not understand it! Thank you!

 

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.