[java] What is callback in Android?

I want to understand the concept of callback. I have searched on internet about the callbacks and there are many examples using interface, and one class is calling a method of another class using that interface. But still I can't get the main concept of callbacks, what is the purpose of using callbacks?

This question is related to java android

The answer is


CallBack Interface are used for Fragment to Fragment communication in android.

Refer here for your understanding.


Callback can be very helpful in Java.

Using Callback you can notify another Class of an asynchronous action that has completed with success or error.


It was discussed before here.

In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.


You create an interface first, then define a method, which would act as a callback. In this example we would have two classes, one classA and another classB

Interface:

public interface OnCustomEventListener{
  public void onEvent();   //method, which can have parameters
}

the listener itself in classB (we only set the listener in classB)

private OnCustomEventListener mListener; //listener field

//setting the listener
public void setCustomEventListener(OnCustomEventListener eventListener) {
   this.mListener=eventListener;
}

in classA, how we start listening for whatever classB has to tell

classB.setCustomEventListener(new OnCustomEventListener(){
    public void onEvent(){
       //do whatever you want to do when the event is performed.
    }
});  

how do we trigger an event from classB (for example on button pressed)

if(this.mListener!=null){
   this.mListener.onEvent();
}

P.S. Your custom listener may have as many parameters as you want

Source


I am using in the following case: In UI I got an action from a button, for eg. the user want to download an 500mb file. Thank I will initialize the background engine (AsyncTask class) and pass parameters to him. On the UI I will show a blocking progress dialog and disable the user to make any other clicks. The question is: when to remove the blocking from UI? the answer is: when the engine finished with success or fail, and that can be with callbacks or notifications.

What is the difference between notification and callbacks it is another question, but 1:1 is faster the callback.