Understanding Callback Methods with Examples

OneSpan Team,

In modern application development, Event-Driven development has been increasing in popularity. Developers nowadays are widely using Synchronous and Asynchronous callbacks in their applications to achieve flexibility.  While the concept is known as Callbacks in the Java community, it is called Delegates in the .NET world. Today, we will be explaining Callback methods in a clear way, with three simple examples. 

What’s a Callback?

Callbacks is a mechanism in Object Oriented Programming that allows an application to handle subscribed events, arising at runtime, through a listener interface. The subscribers will need to provide a concrete implementation of the interface abstract methods. This way, whenever the specified event is triggered, the predefined actions associated with it will execute in the order they were defined.

Examples:

Basic Instance:

In this example we will explain the concept of creating a callback in four steps:
First, Create a callback interface and declare inside it the methods to be called back. These abstract methods represent the events which will trigger the callback methods in the main class.


Let’s call the interface ActionListenerCallback , with the abstract methods onActionSuccess and onActionFailure , which will be passed with a concrete implementation as an argument to the setActionListener , through an anonymous instance of the ActionListenerCallback.

 public interface ActionListenerCallback  {

      public void onActionSuccess(String successMessage;

      public void onActionFailure(Throwable throwableError);

  }

Create the WorkerClass , it is the class that will produce the event and trigger the appropriate callback methods based on the predefined conditions. The WorkerClass contains the setActionListener method, which will allow the subscriber objects to send their callbacks as an argument, through an anonymous ActionListenerCallback  interface.

 

public class Worker {

ActionListenerCallback  callBack;

public Worker() {

 //initializing the callback object from the constructor 
        this.callBack = null; 

    }

    public void setActionListener(ActionListenerCallback  callBack) {

        this.callBack = callBack;

        System.out.println("Performing some task, prior to invoking the callback"); 

         if (this.callBack!= null) { 

            callBack.onActionSuccess (successMessage); 

else
            callBack.onActionFailure (throwableError); 

    }

} 

Provide the desired response to the event by defining the callback methods in the SubscriberActivityclass. In the code below, the setActionListenermethod will attach the anonymous ActionListenerCallback to the worker object making it ready to respond when the specified event is triggered.

public class SubscriberActivity extends Activity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        Worker worker = new Worker ();
        worker.setActionListener(new ActionListenerCallback () {

            @Override

            public void onActionSuccess(StringsuccessMessage) {

            System.out.println("The event has been triggered successfully");

            }
          
            @Override

            public void onActionFailure(Throwable throwableError) {

            
            System.err.println("Error: " + throwableError.getMessage());

            }

        });

    }

}

Android Callback Listeners Example:

We have chosen to provide the second example form the Android framework due to its popularity. Android maintains the interaction between the end-user and the application using the widely used Listener Design Pattern. All the UI components, like a button, inherit from the View class, which in turns implements the Callback interface from android.graphics.drawable package. The View class contains all the event listeners to intercept the various events from the UI. Each of these listeners contain only one callback method.

Let’s take a look into one of the most used callbacks in Android, onClick(), it is declared in View.OnClickListenerinterface as seen below . When the click event happen on the respective UI item, the OnClick() method will be triggered and perform the operations defined by the subscribing objects. 

public static interface OnClickListener()  {

    void onClick(View view);

}

Then, the callback code is defined and attached to the button using the OnClickListenerinterface, waiting for the click event to be triggered. The UI item which is a button in this example uses the setOnClickListener method from its superclass View to subscribe to the event and provide its own implementation of the callback function.

Button button = (Button) findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View view) {

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

        startRegistration();

    }

});

For a full reference, below is the setOnClickListener in the View class.


public void setOnClickListener(@Nullable View.OnClickListener l) {

    throw new RuntimeException("Stub!");

} 

Orchestration SDK Callback Example:

To maintain the responsiveness of the integrated application, the Orchestration SDK employs an asynchronous approach, in which the integrator will need to provide concrete implementations of the callback methods for the different activities provided by the orchestration SDK. This way, the integrating object is registered with a listener, and it could continue its execution with another operation. Whenever an event occurs, the orchestration SDK will execute the code linked with that event, including the callback methods defined by the integrating developer.

NOTE: The callback methods are called from the UI thread on Android, and from the main thread on iOS.

One example of the Orchestration SDK callback methods’ utilization is in the MainActivityof the sample application. The sendCommandToServermethod will instantiate a CommandSender object with an anonymous object of the CommandSenderCallbackinterface. This anonymous will carry the concrete implementation of both onCommandSendingFailureandonCommandSendingSuccess. Also, the application context will be provided as an argument to the CommandSenderobject. 
Following this setup, whenever the Asynchronous execute method get run on the CommandSender
Object, the callback methods will be called the in the order determined. 

private void sendCommandToServer(String command) {

    CommandSender commandSender = new CommandSender(getApplicationContext(), new CommandSenderCallback() {

        @Override

        public void onCommandSendingFailure() {

            UIUtils.hideProgress(progressDialog);

            UIUtils.displayAlert(MainActivity.this, getString(R.string.dialog_error_title), getString(R.string.dialog_error_content_sending));

        }

        @Override

        public void onCommandSendingSuccess(String serverCommand) {

            orchestrator.execute(serverCommand);

        }

    });
    
    commandSender.execute(command);

This tutorial was an entry point for the Callback methods concept, meant to provide a basic understanding of the flow between the different activities of the OneSpan Mobile Security Suite. We will rely on this basic concept as we dive into this further, in upcoming blogs. Meanwhile, if you have any questions, reach out to us on the OneSpan Community Portal Forums.

onespan mobile security suite
Webpage

Mobile Security Suite

Optimize your customers’ mobile experience, protect your customers’ personal data, and reduce fraud with state-of-the-art authentication and mobile application security.

Learn more

The OneSpan Team is dedicated to delivering the best content to help you secure tomorrow's potential. From blogs to white papers, ebooks, webinars, and more, our content will help you make informed decisions related to cybersecurity and digital agreements.