- Interface Class: One interface has to be created. This interface reference will be passed from UI class to background class. This will have two callback methods defined.
- Background Operation Class: One class for doing background operation. Which will accept interface reference as parameter. One different conditions this class will notify UI class.
- Calling Class: One class which can call background operation and implement interface class. This class will pass interface reference to background operation class.
CallbackInterface .java
package technical.jungle.com.callback;
/*
* This interface will just play a role of callback. We have
* two callback which will be invoked at two different scenarios.
*/
public interface CallbackInterface {
void notifyInbetween();
void success();
}
CallbackWorkerDemo.java : For background operation
This callback class will accept reference of interface “CallbackInterface”. Once some condition met then notify by first callback and once background work is being performed completely then inform(notify) it back to calling class.
package technical.jungle.com.callback;
public class CallbackDemo {
static CallbackInterface mCallbackInterface = new CallbackInterface() {
// Here notification/callback will be received from background
// operation.
@Override
public void notifyInbetween() {
// callback one
System.out.println(“notifyInbetween”);
}
@Override
public void success() {
// callback two
System.out.println(“success. Code completed.”);
}
};
public static void main(String args[]) {
CallbackWorkerDemo callbackWorkerThread = new CallbackWorkerDemo(
mCallbackInterface);
}
}
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. This callback class will accept reference of interface “CallbackInterface” and notify back to calling class.
package technical.jungle.com.callback;
public class CallbackWorkerDemo {
public CallbackWorkerDemo(CallbackInterface mCallbackInterface) {
// background operation.
for (int i = 0; i < 10; i++) {
// if some condition met, then notify by one callback.
if (i == 5) {
mCallbackInterface.notifyInbetween();
}
}
// Once all success then success callback.
mCallbackInterface.success();
}
}
Output
notifyInbetween
success. Code completed.