How to implement Callback mechanism ( With One Callback – no parameter )

This is all about “how to implement” callback mechanism in Core Java with one interface.

Steps to implement it
  1. Interface Class: One interface has to be created. This interface will be passed from UI class to background class.
  2. Background Operation Class: One class for doing background operation. Which will accept interface reference as parameter.
  3. Calling Class: One class which can call to background operation and implement interface class. 

CallbackInterface .java

This interface will just play a role of callback. Means once some background activity will be performed then that will be notified to hosting class. This interface will be passed from UI class to background class. 

package technical.jungle.com.callback;

public interface CallbackInterface {
void notifyIt();
}

CallbackWorkerDemo.java : For background operation


This callback class will accept reference of interface  “CallbackInterface”. And once background work is being performed then inform(notify) it back to calling class.

package technical.jungle.com.callback;

public class CallbackWorkerDemo {
public CallbackWorkerDemo(CallbackInterface mCallbackInterface) {
try {
// some background operation.
Thread.currentThread().sleep(1000*5);

     catch (InterruptedException e) {
e.printStackTrace();
}
 
    finally{
System.out.println(“finally block”);
}
 
mCallbackInterface.notifyIt();
}
}

CallbackDemo.java

This class will responsible to do some background operation. This class will accept accept interface reference and once background operation is performed then notify back to main class.

package technical.jungle.com.callback;

public class CallbackDemo {
static CallbackInterface mCallbackInterface = new CallbackInterface() {

@Override
public void notifyIt()
 {
        // Here notification/callback will be received from background operation.
System.out.println(“Callback received.”);
}
};

public static void main(String args[]){
//initialize background operation with inteface reference.
CallbackWorkerDemo callbackWorkerThread = new CallbackWorkerDemo(mCallbackInterface);

}
}

Output


finally block
Callback received.

If you like the post then please socialize it. Happy Sharing. Loudly Subscribing.

Leave a Reply

Your email address will not be published. Required fields are marked *