Search code examples
androidibm-mobilefirst

How to achieve interaction between Native and Hybrid Applications in Worklight?


I will start with explaining the use case I am trying to implement. I have two different applications:

  1. Native android application, and
  2. Worklight-based hybrid application

The use case starts with opening native android application. On a particular event I am opening the Hybrid application with some parameters.

In the Hybrid application, I am getting the passed parameters in the native side it, and now I want to use that data in the webview of the application (JavaScript, HTML). How can I achieve that?

For example:
I opened the first android application. Which have one text box and a button. I entered my mobile number in text box and hit the button. On the button click I have code which starts the other hybrid application and passes the mobile number with it.

I am able to extract that mobile number parameter on native side of code. How to pass that to the Web (JavaScript) part of it?

Any help will be appreciated.


Solution

  • I will describe the solution using code snippets.

    First Open the hybrid application from a native application.

    Intent intent = getPackageManager().getLaunchIntentForPackage(“URI Of Target Application”);
    intent.putExtra("someData", someData);
    startActivity(intent);
    

    Now Worklight based hybrid application will start and from native part we will extract that passed data and store it in shared preferences:

    Bundle dataBundle = getIntent().getExtras();
    String someData = dataBundle.getString("someData");
    sharedpreferences = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
    sharedpreferences.edit().putString("someData", someData);
    sharedpreferences.commit();
    

    Now make a plugin which you can call after the web part is ready for use.

    SharedPreferences sharedpreferences = cordova.getActivity().getSharedPreferences(MyPREFERENCES,cordova.getActivity().MODE_PRIVATE);
    if(sharedpreferences!=null) {
         String param = sharedpreferences.getString("someData", "-1");
         sharedpreferences.edit().remove("someData").commit();
         callbackContext.success(param); 
    }
    

    Call that plugin on web side of Worklight based hybrid application.

    function onSuccessSharedData (param) {
         Param is the passed parameter
    } 
    Cordova.exec(onSuccessSharedData, onFailure, "pluginName", "action", []);