+

Search Tips   |   Advanced Search

Sending actions and data objects from JavaScript code to native code

IBM MobileFirst Platform Foundation lets you send actions with optional data objects from JavaScript to C#, iOS or Java code.

You might want to send a custom action from JavaScript code to native code, for example, for updating the user interface. Any object can receive actions. To do so, it must implement the WLActionReceiver interface (for Android, Windows Phone 8) or protocol (for iOS).

Android

Example

public class MyReceiver implements WLActionReceiver{
  void onActionReceived(String action, JSONObject data){
  //process received action
}

Actions are always delivered on a background thread. To update the application user interface from the received action, do so on a main user interface thread, for example using the Context.runOnUIThread method.

iOS

Example

// MyReceiver.h file #import "WLActionReceiver.h";
@interface MyReceiver: NSObject <WLActionReceiver>{}
@end
// MyReceiver.m file @implementation MyReceiver
-(void)onActionReceived:(NSString *)action withData:(NSDictionary *)data{
    // process received action
}
@end 

Actions are always delivered on a background thread. To update the application user interface from the received action, do so on a main user interface thread, for example using the performSelectorOnMainThread method.

Windows Phone 8

Example

public class MyReceiver : WLActionReceiver {
  public void onActionReceived(string action, JObject data) {
  //process received action  
}

Actions are received by action receivers. Actions that cannot be delivered immediately are queued by the MobileFirst framework and delivered as soon as a suitable action receiver is registered.

  1. Add an action receiver in native code. For example:

    Android

      WL.getInstance().addActionReceiver(myReceiver);

    iOS

      [[WL sharedInstance] addActionReceiver:myReceiver];

    Windows Phone 8

      WL.getInstance().addActionReceiver(myReceiver);

  2. Send action from JavaScript code to native code. For example:
    var data = {someproperty:1234};
    WL.App.sendActionToNative("doSomething", data);

  3. Implement the native onActionReceived. For example:

    Android

    void onActionReceived(String action, JSONObject data){
     if (action.equals("doSomething")){
     //perform  required actions, e.g., update native user interface  }
    }

    iOS

    -(void) onActionReceived:(NSString *)action withData:(NSDictionary *) data {
        if ([action isEqualToString:@"doSomething"]){
           // perform  required actions, e.g., update native user interface     }
    }

    Windows Phone 8

    void onActionReceived(string action, JObject data) {
     if (action == "doSomething") {
     //perform  required action, e.g., update native user interface  }     
    }


Parent topic: Sending actions and data objects between JavaScript code and native code