[Cordova] Introduction to plugin Development

Source: Internet
Author: User
Tags call back


[Cordova] Introduction to Plugin Development overview


Cordova's design concept is to render Web pages through Web controls on the app, allowing web developers to manipulate familiar languages and tools to develop apps. The use of web pages to render functional content, it is true to meet most of the functional requirements, but because the app's usage is different from the web, some apps need to function like: Make phone calls, scan barcodes ... And so on, can not be achieved simply using web development technology.



To enable Web pages to meet more app functionality requirements, Cordova provides a plugin mechanism to enable Web pages to mount and invoke functional modules developed by native development technologies. When a developer encounters a functional requirement that web development technology cannot achieve, it is possible to download and use the various common plugin function modules available from the Cordova official website (https://cordova.apache.org/plugins/). And even in the face of special functional requirements, Cordova also provides a way for developers to develop their own custom-made plugin function modules.



This article describes how to build a Cordova plugin function module that enables developers to use native development techniques to develop plugin function modules in Cordova for use in Web pages, allowing Web pages to meet more app functionality needs. The main is to leave a record for themselves, but also hope to help the need for developers.





Cordova Plugin Metadata


The Cordova plugin function module is stored as a folder in a native file system or a remote git server. When you use Visual Studio to develop a Cordova project, you can automatically complete the action of the plugin function module by simply entering the file path or the server path.






When you mount the Plugin function module, Visual Studio reads the "plugin.xml" under the folder. This XML file defines the relevant setting items for the Plugin function module, which are used to describe the plugin function module, and the main items are:


    • Id:plugin identifier
    • Version:plugin version
    • Name:plugin Name
    • Description:plugin description
    • License:plugin licensing Mode
    • Js-module: Setting items for each JavaScript module
    • Platform: Setting items for each execution platform
<? xml version = "1.0" encoding = "UTF-8"?>
<plugin xmlns = "http://apache.org/cordova/ns/plugins/1.0"
         id = "clk-cordova-sample"
         version = "1.0.0">

     <!-metadata->
     <name> CLK Cordova Sample </ name>
     <description> Description of CLK Cordova Sample </ description>
     <license> Apache 2.0 </ license>

     <!-javascript->
     <js-module> ... </ js-module>
     <js-module> ... </ js-module>

     <!-android->
     <platform name = "android"> ... </ platform>

     <!-ios->
     <platform name = "ios"> ... </ platform>

</ plugin>
Android Platform pluginplatform Metadata


Cordova when compiling Android Platform plugin, it will first build a compiled Android project and read the Platform setting block labeled Android in Plugin.xml. Compile parameters as compile-time.


<!-- android -->
<platform name="android">        
    <!-- config -->
    <config-file target="res/xml/config.xml" parent="/*">
        <feature name="NotificationService">
            <param name="android-package" value="com.clk.cordova.sample.NotificationService"/>
        </feature>
    </config-file>        
    <!-- source -->
    <source-file src="src/android/NotificationService.java" target-dir="src/com/clk/cordova/sample/" />
</platform>
Source-file


When the Cordova reads to the Source-file set block of the Android platform's set block, it copies the files specified in each Source-file setting block to the specified folder in the Android project Target-dir Used for subsequent compilation work. In this example, the meaning of the Source-file setting block is: Copy the plugin Src/android/notificationservice.java file to the Android project src/com/clk/ cordova/sample/folder to compile.


<!-- source -->
<source-file src="src/android/NotificationService.java" target-dir="src/com/clk/cordova/sample/" />




Config-file


The Config-file setting block of the Android platform is special, and this setting block is used to define the category that is provided to the Web page call. In this case, feature name represents the class alias that this plugin provides to the Web page, and param value defines the native class name that actually provides the service, while the remaining set parameters are the fixed parameters required for compilation. In this example, the Config-file setting block represents the meaning that the Web page can use the Notificationservice category alias To call the Android project inside the Com.clk.cordova.sample.NotificationService this native category.


<!-- config -->
<config-file target="res/xml/config.xml" parent="/*">
    <feature name="NotificationService">
        <param name="android-package" value="com.clk.cordova.sample.NotificationService"/>
    </feature>
</config-file>
Native code


Android platform plugin, using the native category developed by native technology, Must inherit org.apache.cordova.CordovaPlugin this category, and then through the Source-file set to join the project compilation, the subsequent can be through the definition of Config-file to provide a Web page call. When a Web page calls the native category, Cordova executes the Execute method of the native category and provides the following:


    • Action: The method name.
      • Because only execute one entry point, use the action to distribute the method, so that a class can provide more methods.
    • Args: Method parameters.
      • The parameter contents of the corresponding method name, in Jsonarray format.
    • Callbackcontext: Method call back.
      • The method succeeds when the call callbackcontext.success the successful result, and the method fails when the call Callbackcontext.error callback error message.
    • Return: Whether to accept the call.
      • Callback True when the method succeeds, and False when the method fails.
package com.clk.cordova.sample;

import org.apache.cordova.*;
import org.json.*;
import android.widget.Toast; 

public class NotificationService extends CordovaPlugin {

    // methods
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

        // show
        if(action.equals("show")) {

            // arguments
            String message = args.getString(0); 

            // execute
            Toast.makeText(this.cordova.getActivity(), message, Toast.LENGTH_LONG).show();

            // return
            return true;
        }

        // default
        return false;       
    }
}
Cordova.exec


After completing the development of the above Android Platform plugin, the Web page can use the unified Cordova.exec method to invoke the native-developed category in the Android execution platform attached to the Cordova plugin. This cordova.exec interface executes the Execute method of the native class and brings in the following content:


    1. Success: Callback function when the method succeeds.
    2. Error: Callback function when the method fails.
    3. Feature:config-file sets the category alias defined by the block.
    4. The method name provided by the action:native category.
    5. The method parameters provided by the args:native category.
cordova.exec(success, error, feature, action, args);
JavaScript Module Plugin


Cordova provides a unified Cordova.exec method that allows Web pages to invoke native-developed plugin functionality. However, the Cordova.exec method needs to bring in five input parameters, plus success, error two callback function implicit callback parameters, plus multi-parameter needs to be wrapped in JSON format ... These trivial tasks will add a lot to the burden of Web developers using the Plugin function module.



To reduce the burden of Web developers using the Plugin function module, developers of the plugin function module can use the JavaScript module mount mechanism provided by Cordova, Add JavaScript program code to the plugin function module to encapsulate the Cordova.exec method to provide a cleaner, more understandable interface for Web developers to use.


    • Before

      cordova.exec(null, null, "NotificationService", "show", [message]);
    • After

      clk.cordova.sample.NotificationService.show("Clark");
Js-module metadata


When compiling each execution platform, Cordova reads all the js-module set blocks in the Plugin.xml, and packs the Js-module source code specified in each js-module set block. When the application executes, the Cordova core loads the Js-module to provide Web page usage.


    • Name:js-module identifier
    • Src:js-module Source Code
<!-- javascript -->
<js-module name="NotificationService" src="www/clk.cordova.sample.NotificationService.js" >
    ...
</js-module>
Js-module Code


Within each js-module source code, you can attach function functions written using JavaScript through the exports object provided by Cordova, a exports object that encapsulates Js-module functionality. In this example, the Js-module source code on the exports object is appended with a show function to simplify the use of cordova.exec, which is provided to the Web page.


    • Clk.cordova.sample.NotificationService.js

      // methods
      exports.show = function (message) {
          cordova.exec(null, null, "NotificationService", "show", [message]);
      };
Cordova.require


When a Web page needs to use Js-module, you can use the Cordova.require method to get js-module. This cordova.require method identifies and obtains Cordova in the Js-module core using the name set in the Js-module settings block, plus the ID identifier identified in the plugin metadata as an index. In this example, the Web page uses Cordova.require to obtain plugin id:clk-cordova-sample, Js-module name:notificationservice, Encapsulates the Js-module exports object, and calls the show function attached to this exports object.


    • Index.html

      var notificationService = cordova.require("clk-cordova-sample.NotificationService");
      
      notificationService.show("Clark");
Clobbers


In order to further simplify the way to obtain Js-module, Cordova also provides clobbers settings on the Js-module set block in Plugin.xml. When the application executes, Cordova Core load Js-module provide the Web page to use, if defines the target setting parameter clobbers provides, Cordova Core will automatically encapsulate Js-module object To the object defined by target, so that the Web page can be called directly.



In this example, Js-module defines a clobbers target, After loading clk.cordova.sample.NotificationService.js, the Cordova Core will encapsulate js-module exports objects and store them in Clk.cordova.sample.NotificationService On this object. Subsequent web pages can invoke the show function appended to this exports object as long as the clk.cordova.sample.NotificationService.show is used directly.


    • Clobbers

      <!-- javascript -->
      <js-module name="NotificationService" src="www/clk.cordova.sample.NotificationService.js" >
          <clobbers target="clk.cordova.sample.NotificationService" />
      </js-module>
    • Index.html

      clk.cordova.sample.NotificationService.show("Clark");
Sample Download


Sample program code:



[Cordova] Introduction to plugin Development


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.