{{announcement.body}}
{{announcement.title}}

Cordova HMS Binding

DZone 's Guide to

Cordova HMS Binding

Breaking down what Cordova is, how to set up an application using CLI, and how to integrate the Cordova application with HMS bindings.

· Open Source Zone ·
Free Resource

In this article I’m going to show you how to integrate Cordova application with HMS bindings. But first, let’s talk about what is Cordova and how to settings up an application using CLI.

What is Cordova?

Cordova is an open-source mobile development framework. It allows you to use standard web technologies such as HTML5, CSS3, and JavaScript for cross-platform development, avoiding each mobile platforms’ native development language. Applications execute within wrappers targeted to each platform and rely on standards-compliant API bindings to access each device’s sensors, data, and network status.

There are several components to a Cordova application. The following diagram shows a high-level view of the Cordova application architecture.

Use Cordova if you are:

  • a mobile developer and want to extend an application across more than one platform, without having to re-implement it with each platform’s language and toolset.
  • a web developer and want to deploy a web app that’s packaged for distribution in various app store portals.
  • a mobile developer interested in mixing native application components with a WebView (browser window) that can access device-level APIs, or if you want to develop a plugin interface between native and WebView components.

Setting Up Environments

Cordova command-line runs on Node.js and is available on NPM.

To ensure your machine has these environments;

  • Open a command prompt or Terminal, and type npm -v and node -v
  • I assume that, you’ve already installed these environments.
  • Open a command prompt or Terminal, and type npm install -g cordova
  • Once you finished installation, we’re ready to create cordova project.
  • Create a blank Cordova project using the command-line tool. Navigate to the directory where you wish to create your project and type cordova create <path> NAME_OF_APP.
  • For a complete set of options, type cordova help create.
  • After creating a Cordova project, navigate to the project directory. From the project directory, you need to add a platform for which you want to build your app.
  • To add android platform, type cordova platform add android.
  • Connect your phone to Machine and command line, run cordova run android. Application will be deploy on your phone.

Plugins.xml

Plugins are an integral part of the Cordova ecosystem. They provide an interface for Cordova and native components to communicate with each other and bindings to standard device APIs. This enables you to invoke native code from JavaScript.We will implement our plugin for executing scripts,
customized gradle file and modify manifest file.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

<hook src="scripts/lib/moveAgconnectServices.js" type="before_plugin_install" />   

     <!-- hook for add maven repositories and agc plugin-->   

       <hook src="scripts/android/after_plugin_install.js" type="after_plugin_install" />   

       <hook src="scripts/android/before_plugin_uninstall.js" type="before_plugin_uninstall" />   

        <framework custom="true" src="src/android/build.gradle" type="gradleReference" />   

         <!-- Push Kit dependency-->   

       <framework src="com.huawei.hms:push:4.0.0.300" />   

       <framework src="com.huawei.agconnect:agconnect-core:1.3.1.300" />   

       <config-file target="res/xml/config.xml" parent="/*">   

           <feature name="PushPlugin">   

               <param name="android-package" value="com.hms.cordova.plugin.PushPlugin"/>   

           </feature>   

       </config-file>   

         <config-file parent="/manifest/application" target="AndroidManifest.xml">   

            <service android:exported="false" android:name="com.hms.cordova.plugin.PushService">   

           <intent-filter>   

               <action android:name="com.huawei.push.action.MESSAGING_EVENT" />   

           </intent-filter>   

       </service>   

         </config-file>   

       <source-file src="src/android/PushPlugin.java" target-dir="src/com/hms/cordova/plugin" />   

       <source-file src="src/android/PushService.java" target-dir="src/com/hms/cordova/plugin" />   

Let’s focus on it step by step;

<hook src=”scripts/lib/moveAgconnectServices.js” type=”before_plugin_install” />

This hook parameter provides us to execute our custom script before the plugin install. Therefore if we need to custom configuration, the hook parameter provides us to handle it. As well as it provides after install, after uninstall and before uninstall.

<framework custom=”true” src=”src/android/build.gradle” type=”gradleReference” />

framework parameter identifies a framework (usually part of the OS/platform) on which the plugin depends. We’re using it for the customized build.gradle file to add dependencies.

<config-file target=”res/xml/config.xml” parent=”/*”> <feature name=”PushPlugin”> <param name=”android-package” value=”com.hms.cordova.plugin.PushPlugin”/> </feature> </config-file>

config-file parameter identifies an XML-based configuration file to be modified. We’re using it for used to specify the push plugin. Also used for customized AndroidManifest.xml to add permissions.

<source-file src=”src/android/PushPlugin.java” target-dir=”src/com/hms/cordova/plugin” />

source-file parameter identifies executable source code that should be installed into a project. We’re using for our plugins which are PushPlugin and AnalyticsPlugin.


Writing Android Java Plugin

Writing a plugin requires an understanding of the architecture of Cordova-Android. Cordova-Android consists of an Android WebView with hooks attached to it. These plugins are represented as class mappings in the config.xml file.

A plugin will consist of at least a single Java class that extends the CordovaPlugin class. A plugin must override one of the execute methods from CordovaPlugin.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

public class PushPlugin extends CordovaPlugin {   

   private static final String TAG = PushPlugin.class.getSimpleName();   

   @Override   

   public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) {   

       if (action.equals("getToken")) {   

           getToken(callbackContext);   

       }   

       return true;   

   }   

   private void getToken(CallbackContext callbackContext) {   

       Log.i(TAG, "get token: begin");   

       try {   

           String appId = AGConnectServicesConfig.fromContext(cordova.getContext()).getString("client/app_id");   

           String pushToken = HmsInstanceId.getInstance(cordova.getContext()).getToken(appId, "HCM");   

           if (!TextUtils.isEmpty(pushToken)) {   

               Log.i(TAG, "******TOKEN******:" + pushToken);   

               PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, pushToken);   

               callbackContext.sendPluginResult(pluginResult);   

           }   

       catch (Exception e) {   

           Log.e(TAG, "getToken Failed, " + e);   

           PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR, e.getMessage());   

           callbackContext.sendPluginResult(pluginResult);   

       }   

   }   

}   


We compare the value of the action parameter, and dispatch the request off to a (private) method in the class, optionally passing some of the parameters to the method. We’re getting parameter from JavaScript’s exec function gets passed into the Plugin class's execute method than called getToken() method.

Inside getToken() method, we’re using HMS java code to provide us token depends on our appId, than we received token, return to the callback with tokenId with PluginResult object. It will be pass data from java to JavaScript UI layer of our android application.

1

2

3

4

5

6

7

getToken: function() {   

   window.plugins.PushPlugin.getToken(function(res) {   

       alert( res);   

   }, function(err) {   

      alert(err);   

   });   

   },   

In the UI layer of android, we’re implementing a button and add on_click trigger. As return from PluginResult in CordovaActivity, show, and alert of token which received from HmsInstanceId.

Happy codding.

References

Documentation - Apache Cordova

HUAWEI Developer Forum

Topics:
android, cordova, integration, java, opensource

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}