cordova3.X uses grunt to generate plugin custom plug-in skeleton

Keywords: Android Apache Java xml

 

Cordova provides a set of device-related API s through which mobile applications can access native device functions such as cameras, microphones and so on in JavaScript. Cordova also provides a unified set of JavaScript class libraries, as well as native background code for devices used in these libraries.

 

I. Installation of cordova

npm install -g cordova

 

II. Creating Projects

cordova create hello com.blue.sky.hybrid.app.hello HelloWorld

 

3. Adding Platform Support

cd hello

cordova platform add android (provided that the SDK of the corresponding mobile system is installed on the system)

 

In windows system:


$ cordova platform add wp8
$ cordova platform add windows
$ cordova platform add amazon-fireos
$ cordova platform add android
$ cordova platform add blackberry10
$ cordova platform add firefoxos

In mac system:


$ cordova platform add ios
$ cordova platform add amazon-fireos
$ cordova platform add android
$ cordova platform add blackberry10
$ cordova platform add firefoxos

 

Common orders


Cordova platforms view currently installed mobile platforms


cordova platform rm android removal system support


cordova build or cordova build android compilation


cordova emulate android simulator running program

 

Need to install ant: configure system environment variables, ant needs JAVA support, determine system installation JDK, and configure JAVA environment variables.

ANT_HOME   D:\tool\apache-ant-1.9.0
PATH       %ANT_HOME%\bin
CLASSPATH  %ANT_HOME%\lib


Cordova run Android USB

cordova platform update android update android platform

 

Plug-in Management

cordova plugin search bar code search plug-in
cordova plugin add org.apache.cordova.console adds plugin support, with multiple spaces separated
cordova plugin add org.apache.cordova.console@latest latest version
cordova plugin add org.apache.cordova.console@0.2.1 specified version
cordova plugin add https://github.com/apache/cordova-plugin-console.git
cordova plugin add https://github.com/apache/cordova-plugin-console.git#r0.2.0 version
cordova plugin add https://github.com/someone/aplugin.git#:/my/sub/dir subdirectory

 

Cordova plugins view installed plugins
cordova plugin rm org.apache.cordova.console removes plugins

 

6. Custom Plug-ins

After learning so much, I am ready to write a custom plug-in by myself, instead of inputting it on the command line: cordova plugin create. com.blue.sky.test. It doesn't work. After consulting the data, I find that without this command, people on the Internet are creating directories manually, which is too troublesome. So I write a command with grunt to generate cordova plugin skeleton through template.

 

>> The online approach is probably like this:

After Cordova 3.X, the plug-in can not be added manually by itself. Once the plug-in is added manually, as long as the Cordova builds, the data will be erased immediately.

Therefore, to add plug-ins after 3.X, you need to add plug-ins in the way of Cordova plungin adding "the path of your local plug-ins".

1. Create a new folder named after your plug-in, such as Test Plugin.

2. Create two new folders and one new file in the folder. The two folders are SRC and www. In src, put the java code of your plug-in, and in www, put the corresponding js file. At the same level with SRC and WWW folders, build plugin.xml.

 

>> Using grunt template to generate cordova plugin skeleton

Idea: cordova plugin consists of three files:

1. Native implementation class inheriting cordovaActivity

2. Writing javascript code

3. Write plugin.xml configuration file

 

In this case, you can use grunt to generate cordova plugin skeleton through templates.

First, look at the project code structure:

 

Step 1: Develop a cordova plugin template

 

The template is as follows:

src/android/template.txt inherits the Native implementation class of cordovaActivity

package <%=pkgName%>;

import java.util.TimeZone;

import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaInterface;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.provider.Settings;

public class <%=className%> extends CordovaPlugin {

    public <%=className%>() {

    }

    /**
     * Executes the request and returns PluginResult.
     *
     * @param action            The action to execute.
     * @param args              JSONArry of arguments for the plugin.
     * @param callbackContext   The callback id used when calling back into JavaScript.
     * @return                  True if the action was valid, false if not.
     */
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

        /// TODO custom implementation

        return true;
    }

}

  

www/template.txt javascript template

var channel = require('cordova/channel'),
  utils = require('cordova/utils'),
  exec = require('cordova/exec'),
  cordova = require('cordova');

function <%=className%>() {

}

module.exports = new <%=className%>();

  

plugin.xml Plug-in Compiler Generates android Project Code Configuration File

<?xml version="1.0" encoding="UTF-8"?>
<!--Plug-in unit id Number, and package.json Keep the same version number, and package.json Bring into correspondence with-->
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
        id="<%=pkgName%>" version="0.1">
    <!--Plug-ins in cordova The following name, Test.js in exec Interface name, consistent-->
    <name><%=className%></name>
    <description>Cordova Plugin</description>
    <license>Apache 2.0</license>
    <!--and package.json Bring into correspondence with-->
    <keywords></keywords>
    <repo></repo>
    <issue></issue>
    <!--Plug-in unit js Interface file configuration information, plug-in in android-->
    <!--src="www/Test.js"Written for js File path, and js The class names invoked in the-->
    <js-module src="www/<%=className%>.js" name="<%=className%>">
        <!--Plug-ins in js Class name called in-->
        <clobbers target="<%=className%>" />
    </js-module>

    <!-- android -->
    <platform name="android">
        <config-file target="res/xml/config.xml" parent="/*">
            <!--Plug-ins in java The name of the interface on the end, which is consistent with the name of the interface in the previous file-->
            <feature name="<%=className%>">
                <!--The plug-in interface corresponds to java Code path-->
                <param name="android-package" value="<%=pkgName%><%=className%>"/>
            </feature>
        </config-file>

        <!--The required permission declaration for the plug-in is self-defined as needed-->
        <config-file target="AndroidManifest.xml" parent="/*">
            <uses-permission android:name="android.permission.INTERNET" />
            <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
            <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
        </config-file>

        <!--The source file path and the target file path, src Written for already java Code path, target-dir Generated for need android In the project, java Source path, with the above java Code paths are consistent-->
        <source-file src="<%=sourceSrc%>" target-dir="<%=targetDir%>"/>

    </platform>

</plugin>

 

Using Node.js + grunt to generate skeleton code based on template: grunt plugin:create:com.blue.sky.test:Test

grunt.registerTask('plugin:create', 'Custom Plug-in Parameters One Package Name Parameters Two Plug-in Class Names', function (arg1, arg2, arg3) {
    grunt.log.writeln(">>>>length:" + arguments.length);
    if (arguments.length === 2) {

      var pkgName = arg1;
      var fileName = arg2;
      var platform = arg3 || "android";
      var pluginDir = "temp/" + arg1;
      var tplNativeCode = "template/src/" + platform + "/template.txt";
      var tplJSCode = "template/www/template.txt";
      var tplPlugin = "template/plugin.xml";

      var srcFileName = pluginDir + "/src/" + platform + "/" + arg2 + ".java";
      var jsFileName = pluginDir + "/www/" + arg2 + ".js";
      var configFileName = pluginDir + "/plugin.xml";

      grunt.log.writeln("start create plugin:" + arg1);

      grunt.file.mkdir(pluginDir);

      // Create plug-in java classes
      grunt.file.mkdir(pluginDir + "/src/" + platform);
      grunt.file.write(srcFileName, grunt.file.read(tplNativeCode));
      var content = grunt.file.read(srcFileName);
      var text = grunt.template.process(content, {data: {"pkgName": pkgName + "." + fileName, "className": fileName}});
      grunt.file.write(srcFileName, text);

      // Create plug-in javascript
      grunt.file.mkdir(pluginDir + "/www");
      grunt.file.write(jsFileName, grunt.file.read(tplJSCode));
      var jsContent = grunt.file.read(jsFileName);
      var jsText = grunt.template.process(jsContent, {data: {"className": fileName}});
      grunt.file.write(jsFileName, jsText);

      // Create plugin configuration file plugin.xml
      var configContent = grunt.file.read(tplPlugin);
      var configText = grunt.template.process(configContent,
        {
          data: {
            "pkgName": pkgName,
            "className": fileName,
            "sourceSrc":"src/"+ platform + "/" + fileName +  ".java",
            "targetDir":"src/" + pkgName.replace(/\./g,"/")
          }
        }
      );
      grunt.file.write(configFileName, configText);


      grunt.log.writeln("create plugin success");

    } else {
      grunt.log.writeln("The command format is incorrect. grunt plugin:create Package Name Plug-in Class Name");
    }
  });

  

Use Cordova plugin to add "Locally Customized Plug-in Code"

cordova plugin add "D:\Project\workspace\phonegap\hello\temp\com.blue.sky.test"

After running, you will see the com.blue.sky.test plug-in under the plugins directory (see the project results chart).

 

Run the cordova run android command packer to the phone

After running, look under the platforms directory and generate custom related code, as shown in the following figure:

 

summary

By using grunt to generate cordova plugin, the plugin skeleton can be created in many ways, and the tedious steps can be omitted. Of course, this demo only implements plugin for android platform. If it is easy to support ios and wp, only need to add the corresponding template and mapping relationship.

 

Reprinted at: https://www.cnblogs.com/hubcarl/p/4207066.html

Posted by codepoet on Wed, 26 Jun 2019 13:59:06 -0700