All Products
Search
Document Center

Mobile Platform as a Service:Custom APIs

Last Updated:May 15, 2024

This topic describes custom APIs from the following two aspects:

  • The Mriver Tiny App calls a custom API from the client.

  • The client sends a custom event to the Mriver Tiny App.

The Mriver Tiny App calls a custom API from the client

Perform the following steps:

  1. Customize an API on the client.

    • The custom class inherits from SimpleBridgeExtension.

      public class CustomApiBridgeExtension extends SimpleBridgeExtension{
      }
      Important

      Do not confuse the class with a method.

    • Customize a method. Sample code:

      public class CustomApiBridgeExtension extends SimpleBridgeExtension{
          @ActionFilter
          public void tinyToNative(@BindingApiContext ApiContext apiContext,
                                   @BindingRequest JSONObject params,
                                   @BindingParam("param1") String param1,
                                   @BindingParam("param2") String param2,
                                   @BindingCallback BridgeCallback callback) {
              ···
          }
      }
      • tinyToNative indicates the call method in the Mriver Tiny App, which needs to be added to @ActionFilter.

      • The parameters in the method are passed from the Mriver Tiny App and some context and bridge on the client. Add or delete the parameters as needed. For more information, see Customize method parameters.

    • Generate a JSONObject result and return the result to the Mriver Tiny App. Sample code:

      public class CustomApiBridgeExtension extends SimpleBridgeExtension{
          @ActionFilter
          public void tinyToNative(@BindingApiContext ApiContext apiContext,
                                   @BindingRequest JSONObject params,
                                   @BindingParam("param1") String param1,
                                   @BindingParam("param2") String param2,
                                   @BindingCallback BridgeCallback callback) {
              ···
              JSONObject result = BridgeResponse.SUCCESS.get();
              result.put("custom_message","value");
        // Return the result to the Mriver Tiny App.
              callback.sendJSONResponse(result);
          }
      }

      Sample code remarks:

      • If the JSONObject result is generated, call:

        JSONObject result = BridgeResponse.SUCCESS.get();

        If the JSONObject result is not generated, call:

        JSONObject result = BridgeResponse.Error.newError(errorCode,errorMessage).get();
      • Add custom parameters to the result.

        result.put("custom_message","value");
      • The callback that returns the final JSONObject result to the Mriver Tiny App is @BindingCallback BridgeCallback callback in the custom method.

        callback.sendJSONResponse(result);
    • The custom parameters are described as follows:

      • @BindingId: The String type. Pass in the workId of the current communication.

      • @BindingNode: The Scope type, which can be App.class or Page.class. Pass in the current app or page according to the framework type.

      • @BindingApiContext: The ApiContext type. Use the instance to obtain the context of the current API.

      • @BindingExecutor: The Executor type. Select a different Executor and execute the corresponding logic in its thread. The following table shows the name, description, and priority of the Executors.

        Executor type

        Description

        Priority

        ExecutorType.SYNC

        Execute directly without switching the thread to facilitate encapsulation.

        None

        ExecutorType.UI

        Execute the backend task with the highest priority that the frontend UI depends on. Queuing is not allowed.

        {@link Thread#NORM_PRIORITY}

        ExecutorType.URGENT_DISPLAY

        Execute the backend task with the highest priority that the frontend UI depends on. Queuing is not allowed.

        {@link Thread#MAX_PRIORITY}

        ExecutorType.URGENT

        Execute the backend task with the highest priority that the frontend UI depends on. Queuing is not allowed.

        {@link Thread#NORM_PRIORITY}

        ExecutorType.NORMAL

        Execute the backend task that is normal and not urgent. Queuing is allowed.

        {@link Thread#MIN_PRIORITY}

        ExecutorType.IO

        Execute the task of persistent file I/O operations. The time consumption can be estimated. Either the task succeeds or an exception occurs.

        {@link Thread#MIN_PRIORITY}

        ExecutorType.NETWORK

        Execute the backend task related to the network. The time consumed depends on the condition. A typical scenario is that an RPC request is initiated.

        {@link Thread#MIN_PRIORITY}

        ExecutorType.IDLE

        The idle thread pool, which is used for time-insensitive tasks such as tracking points. The task can be executed in a single thread pool.

        None

      • @BindingRequest: The JSONObject type. The parameters from the Mriver Tiny App are passed in as JSONObject.

      • @BindingParam: The String type, which corresponds to the custom parameter key in the Mriver Tiny App. The parameter value types include string, int, long, float, double, and boolean. The default value can be customized.

        @BindingParam(value = "stringParam", stringDefault = "default") String stringParam
        @BindingParam(value = "intParam", intDefault = 1) int intParam
        @BindingParam(value = "longParam", longDefault = 9223372036854775807L) long longParam
        @BindingParam(value = "floatParam", floatDefault = 1.0F) float floatParam
        @BindingParam(value = "doubleParam", doubleDefault = 1.79769313486231570e+308d) double doubleParam
        @BindingParam(value = "booleanParam", booleanDefault = true) boolean booleanParam
      • @BindingCallback: The BridgeCallback type. The result can be sent to the Mriver Tiny App using BridgeCallback.

    • Sample code

      public class CustomApiBridgeExtension extends SimpleBridgeExtension {
      
          private static final String TAG = "CustomApiBridgeExtension";
      
          @ActionFilter
          public void tinyToNative(@BindingId String id,
                                   @BindingNode(App.class) App app,
                                   @BindingNode(Page.class) Page page,
                                   @BindingApiContext ApiContext apiContext,
                                   @BindingExecutor(ExecutorType.UI) Executor executor,
                                   @BindingRequest JSONObject params,
                                   @BindingParam("param1") String param1,
                                   @BindingParam("param2") String param2,
                                   @BindingCallback BridgeCallback callback) {
              RVLogger.d(TAG, "id: "+id+
                      "\napp: "+app.toString()+
                      "\npage: "+page.toString()+
                      "\napiContext: "+apiContext.toString()+
                      "\nexecutor: "+executor.toString());
              RVLogger.d(TAG, JSONUtils.toString(params));
              JSONObject result = BridgeResponse.SUCCESS.get();
              result.put("message", "the client receives parameters: " + param1 + ", " + param2 + "\n return the current package name of the demo: " + apiContext.getActivity().getPackageName());
              // Return the result to the Mriver Tiny App.
              callback.sendJSONResponse(result);
          }
      
      }
      
  2. Register the custom API on the client. After the container is initialized, you can call the registration method to register the custom API. Do not confuse class names.

    MriverEngine.registerBridge(CustomApiBridgeExtension.class);
  3. Call the API in the Mriver Tiny App. Sample code:

    my.call('tinyToNative', {
      param1: 'p1aaa',
      param2: 'p2bbb'
    }, (result) => {
      console.log(result);
      my.showToast({
        type: 'none',
        content: result.message,
        duration: 3000,
      });
    })

    Sample code remarks:

    • The first parameter is action, which is the same as the annotation in the custom @ActionFilter method on the client.

    • The second parameter is a custom one. In the sample code, the client can receive the parameters using @BindingRequest JSONObject or @BindingParam("param1") String param1, in which the param1 and param2 values are strings composed of letters and digits. Here, param1 and param2 are only examples. The value types of custom parameters include string, int, long, boolean, float, and double.

    • The third parameter is the client callback.

The client sends a custom event to the Mriver Tiny App

Perform the following steps:

  1. Register an event in the Mriver Tiny App.

    // The first parameter is the name of the custom event, and the second parameter is the callback.
    my.on('nativeToTiny', (res) = >{
        my.showToast({
            type: 'none',
            content: JSON.stringify(res),
            duration: 3000,
            success: () = >{},
            fail: () = >{},
            complete: () = >{}
        });
    })
  2. Send the event on the client.

    // Simulate the data sent.
    JSONObject jo = new JSONObject();
    jo.put("index", index);
    AppManager appManager = RVProxy.get(AppManager.class);
    if (null != appManager) {
        // Obtain the instance of the currently running Mriver Tiny App through AppManager.
        App app = appManager.findAppByAppId("2018080616290001");
        if(null!=app){
            // Send information to the Mriver Tiny App.
            // The first parameter is the current activity page of the Mriver Tiny App, the second parameter is the name of the custom event, and the third parameter is the data sent.
            MriverEngine.sendToRender(app.getActivePage(), "nativeToTiny", jo, null);
        }
    }