Understanding Java Callback Functions

Source: Internet
Author: User

In computer programming, a callback function , or a callback (Callback, which is called by call and back, is returned to the main function after the main function invocation), refers to a piece of executable code that passes through the function arguments to other code. This design allows the underlying code to invoke subroutines defined at the top level. (Wikipedia)

Callback for C

A callback function is a function that is called through a function pointer in c/s + + when you pass a pointer to a function as a parameter to another function. When this pointer is used to invoke the function it points to, we call this function a callback function.

Examples of practical situations:

1. Suppose you want to write a library that provides some sort algorithms. (such as bubble sort, quick sort, shell sort, shake sort, etc.), in order to make the library common, we do not want to embed the sort logic in the sorting algorithm function body, and want to make the algorithm support a variety of data types. At this point, you can use a function pointer to make a callback.

2. Callbacks can also be used for notification mechanisms.

Callback for Java

interfaces are often used in the Java programming language to do callback functions . Java does not allow methods to be used as parameters, so one solution is to define an interface that uses the method signature of the item object as a parameter to the method.

Implementation principle:

You first create a callback object, and then you create a controller object that tells the Controller object which method the callback object needs to be called. The Controller object is responsible for checking whether a scene is present or a condition is satisfied. The method that invokes the callback object automatically when this scenario occurs or when this condition is met.

Take an example of Android Soundrecorder.

1. Define a related interface

// Callback Interface  Public class Implements Oncompletionlistener, Onerrorlistener {        publicinterface  Onstatechangedlistener {        publicvoid onstatechanged (int.  );          Public void onError (int  error);}    }
View Code

2. Class a implements the callback method in the interface interface.

//the Soundrecorder class implements the interface Public classSoundrecorderextendsActivityImplementsRecorder.onstatechangedlistener { Public voidOnError (interror) {Resources res=getresources (); BooleanIsexit =false; String message=NULL; Switch(Error) { CaseRecorder.SDCARD_ACCESS_ERROR:message=res.getstring (r.string.error_sdcard_access);  Break;  CaseRecorder.INTERNAL_ERROR:message=res.getstring (r.string.error_app_internal); Isexit=true;  Break;  CaseRecorder.UNSUPPORTED_FORMAT:message=res.getstring (r.string.error_app_unsupported); Isexit=true;  Break; }}
View Code

3. Class B has a method that takes an interface as a parameter.

     Public void Setonstatechangedlistener (Onstatechangedlistener listener) {        = listener;    }   NULL // referencing callback Objects
View Code

4. The object in class A calls the method in Class B.

class Soundrecorder  Public void onCreate (Bundle icycle) {        new  Recorder ();        Mrecorder.setonstatechangedlistener (this); // incoming callback Object }
View Code

5. Then, when something happens, Class B callback the interface method implemented in Class A by the way it does.

classRecorder >>1.  Public voidStartrecording (intoutputfileformat, String Extension, context context,intAudiosourcetype,intCodectype) {        Try{mrecorder.setaudioencoder (codectype); } Catch(RuntimeException exception) {SetError (Unsupported_format);            Mrecorder.reset ();            Mrecorder.release (); if(Msamplefile! =NULL) Msamplefile.delete (); Msamplefile=NULL; Msamplelength= 0; Mrecorder=NULL; return; }}2. Private voidSetError (interror) {        if(Monstatechangedlistener! =NULL) Monstatechangedlistener.onerror (error); }
View Code

If the above analysis is wrong, please correct me.

Understanding Java Callback Functions

Related Article

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.