[Cordova] The creation and use of Cordova's first plug-in

Cordova plugin development

Goal Description

  • Use cordova to implement a small calculator that can perform addition, subtraction, multiplication and division of integers
  • Package the function of addition, subtraction, multiplication and division into a plug-in, and the cordova project uses the function by calling the interface exposed by the plug-in
  • Calculation is implemented through Android native code (that is to say, the calculation function is placed in the java file, and the js file calls the java code to use the function through the exec module method of cordova
    Please add a picture description

first attempt

Before formal development, build a basic framework, call and understand the default code

Note : Before running the command line, please make sure you have built the cordova + plugman environment, if not, please execute the following command line: (in any directory)

$ npm install -g cordova
$ npm install -g plugman

Goal : run through the first cordova + plugin project, add buttons in index.html, complete the call of the initial method coolMethod and the call of the simple arithmetic method sum

Create a cordova project

First create a cordova project

Create a new CordovaPlugin directory as the root directory, open cmd in the root directory, and execute the following commands in sequence:

$ cordova create MyPlugTest2
$ cd MyPlugTest2
$ cordova platform add android
# 为了使得调试比较方便,可以添加browser平台
$ cordova platform add browser

requires attention:

  • The newly added browser platform cannot call Android java code, that is, it cannot call native code through cordova's exec method.
  • Adding the browser platform is to be able to view and debug some functions through the webpage in time, so as to avoid the need for cordova build android every time and then view it in Android Studio.

Create a plugin project and edit

The next step is to create a new plugin project

In the CordovaPlugin folder, execute:

$ plugman create --name MyPlugin2 --plugin_id MyPlugin2 --plugin_version 0.1.0
$ cd MyPlugin2
$ plugman platform add --platform_name android
$ plugman createpackagejson ./

Modify the js code of the plugin:

// MyPlugin2/www/MyPlugin2.js
var exec = require('cordova/exec');

exports.coolMethod = function (arg0, success, error) {
    
    
    exec(success, error, 'MyPlugin2', 'coolMethod', [arg0]);
};

exports.coolMethodSum = function(arg0, success, error){
    
    
    exec(success, error, 'MyPlugin2', 'sum', arg0);
};

Modify the android code of the plugin:

// MyPlugin2\src\android\MyPlugin2.java:
package MyPlugin2;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * This class echoes a string called from JavaScript.
 */
public class MyPlugin2 extends CordovaPlugin {
    
    

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    
    
        if (action.equals("coolMethod")) {
    
    
            String message = args.getString(0);
            this.coolMethod(message, callbackContext);
            return true;
        }
        else if(action.equals("sum")){
    
    
            callbackContext.success(args.getInt(0) + args.getInt(1));
            return true;
        }
        return false;
    }

    private void coolMethod(String message, CallbackContext callbackContext) {
    
    
        if (message != null && message.length() > 0) {
    
    
            callbackContext.success(message);
        } else {
    
    
            callbackContext.error("Expected one non-empty string argument.");
        }
    }
}

keep

Add plugin for cordova project

Execute in the MyPlugTest2 directory:

$ cordova plugin add ./MyPlugin2

If the addition is unsuccessful, please replace ./MyPlugin2 with the absolute path of MyPlugin2

Note : Here you can originally build a Debug environment by adding - -link parameters:

$ cordova plugin add ../path/to/my/plugin/relative/to/project --link

But I have been reporting errors, too lazy to find the reason, so I gave up

Modify the cordova project code

Modify index.html:

<!-- MyPlugTest2\www\index.html -->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
        <meta name="color-scheme" content="light dark">
        <link rel="stylesheet" href="css/index.css">
        <title>Hello World</title>
    </head>
    <body>
        <div class="app">
            <h1>Apache Cordova</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
                <button onclick="coolMethod()">点击调用Cool</button>
                <button onclick="coolMethodSum(2,3)">点击调用Sum</button>
            </div>
        </div>
        <script src="cordova.js"></script>
        <script src="js/index.js"></script>
    </body>
</html>

Note : Here I deleted this line in the auto-generated code:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">

This is because if this line is added, the browser will add the CSP security standard to prohibit the function calls of the two buttons, so it needs to be deleted

Modify index.js:

// MyPlugTest2\www\js\index.js
function success(msg){
    
    
    alert(msg);
}

function error(msg){
    
    
    alert(msg);
}

function coolMethod(){
    
    
    cordova.plugins.MyPlugin2.coolMethod("cool", success, error);
    alert("cool");
}

function coolMethodSum(x, y){
    
    
    cordova.plugins.MyPlugin2.coolMethodSum([1, 2], success, error);
    alert("sum");
}

Build and run

Preview in the browser (preview, because the method of java cannot be used

Run in the directory of the cordova project:

$ cordova build browser
$ cordova run browser

The effect is as follows:
Please add a picture description
Note: Because the java method cannot be used, the first pop-up box is displayed as

Error:missing command error

this is normal

Build the Android project:

In the cordova project run:

$ cordova build android
# build之后可以直接在Android中打开MyPlugTest2\platforms\android\app
$ cordova run android

Note : If the above command outputs the following error, please ignore it. Just make sure that build success appears, and you can proceed to the next step.
Please add a picture description
Open the MyPlugTest2\platforms\android\app project in Android Studio (please ensure that your Android Studio environment It has been correctly configured and the virtual machine has been added), and after waiting for gradle to compile, it can run as follows (the first and second pop-up boxes have content
Please add a picture description

Complete the topic function

The functional interface design is as follows:
Please add a picture description

modify plugin

Because the previous method of adding plug-ins to the cordova project failed to add using the link parameter, if you need to modify the plug-in source code, you first need to delete the plug-ins introduced in the project

Execute the following command under the cordova project:

$ cordova plugin remove MyPlugin2

The next step is to modify the source code of the MyPlugin2 plugin:

First modify the java source code and add the functions of addition, subtraction, multiplication and division:

// MyPlugin2\src\android\MyPlugin2.java
package MyPlugin2;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MyPlugin2 extends CordovaPlugin {
    
    

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    
    
        if (action.equals("coolMethod")) {
    
    
            String message = args.getString(0);
            this.coolMethod(message, callbackContext);
            return true;
        }
        else if(action.equals("sum")){
    
    
            callbackContext.success(args.getInt(0) + args.getInt(1));
            return true;
        }
        else if(action.equals("minus")){
    
    
            callbackContext.success(args.getInt(0) - args.getInt(1));
            return true;
        }
        else if(action.equals("multiple")){
    
    
            callbackContext.success(args.getInt(0) * args.getInt(1));
            return true;
        }
        else if(action.equals("divide")){
    
    
            callbackContext.success(args.getInt(0) / args.getInt(1));
            return true;
        }
        return false;
    }

    private void coolMethod(String message, CallbackContext callbackContext) {
    
    
        if (message != null && message.length() > 0) {
    
    
            callbackContext.success(message);
        } else {
    
    
            callbackContext.error("Expected one non-empty string argument.");
        }
    }
}

Then modify the JS code:

// MyPlugin2\www\MyPlugin2.js
var exec = require('cordova/exec');

exports.coolMethod = function (arg0, success, error) {
    
    
    exec(success, error, 'MyPlugin2', 'coolMethod', [arg0]);
};

exports.coolMethodSum = function(arg0, success, error){
    
    
    exec(success, error, 'MyPlugin2', 'sum', arg0);
};

exports.coolMethodMinus = function(arg0, success, error){
    
    
    exec(success, error, 'MyPlugin2', 'minus', arg0);
};

exports.coolMethodMultiple = function(arg0, success, error){
    
    
    exec(success, error, 'MyPlugin2', 'multiple', arg0);
};

exports.coolMethodDivide = function(arg0, success, error){
    
    
    exec(success, error, 'MyPlugin2', 'divide', arg0);
};

Modify the cordova project

The modified plugin needs to be reintroduced first:

Execute in the MyPlugTest2 directory:

$ cordova plugin add ./MyPlugin2

If the addition is unsuccessful, replace ./MyPlugin2 with the absolute path of MyPlugin2

Modify index.html:

<!-- MyPlugTest2\www\index.html -->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
        <meta name="color-scheme" content="light dark">
        <link rel="stylesheet" href="css/index.css">
        <title>Hello World</title>
    </head>
    <body>
        <div class="app">
            <h1>Apache Cordova</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
                <button onclick="coolMethod()">点击调用Cool</button>
                <button onclick="coolMethodSum(2,3)">点击调用Sum</button>
            </div>
            <div>
                <label for="input1">参数1</label>
                <input type="text" id="input1"/>
                <br/>
                <label for="input2">参数2</label>
                <input type="text" id="input2"/>
                <div>
                    <button id="sumbtn" onclick="coolMethodSum()">+</button>
                    <button id="minusbtn" onclick="coolMethodMinus()">-</button>
                    <button id="multiplebtn" onclick="coolMethodMultiple()">*</button>
                    <button id="dividebtn" onclick="coolMethodDivide()">/</button>
                </div>
                <label for="input2">计算结果</label>
                <input type="text" id="calcresult"/ disabled>
            </div>
        </div>
        <script src="cordova.js"></script>
        <script src="js/index.js"></script>
    </body>
</html>

Modify index.js

// MyPlugTest2\www\js\index.js
function success(msg){
    
    
    alert(msg);
    document.getElementById("calcresult").value = msg;
}

function error(msg){
    
    
    alert(msg);
}

function coolMethod(){
    
    
    cordova.plugins.MyPlugin2.coolMethod("cool", success, error);
    alert("cool");
}

function coolMethodSum(){
    
    
    x = document.getElementById("input1").value;
    y = document.getElementById("input2").value;
    cordova.plugins.MyPlugin2.coolMethodSum([x, y], success, error);
    alert("sum");
}

function coolMethodMinus(){
    
    
    x = document.getElementById("input1").value;
    y = document.getElementById("input2").value;
    cordova.plugins.MyPlugin2.coolMethodMinus([x, y], success, error);
    alert("minus");
}

function coolMethodMultiple(){
    
    
    x = document.getElementById("input1").value;
    y = document.getElementById("input2").value;
    cordova.plugins.MyPlugin2.coolMethodMultiple([x, y], success, error);
    alert("multiple");
}

function coolMethodDivide(){
    
    
    x = document.getElementById("input1").value;
    y = document.getElementById("input2").value;
    cordova.plugins.MyPlugin2.coolMethodDivide([x, y], success, error);
    alert("divide");
}

rebuild project

In the cordova project run:

$ cordova build android
# build之后可以直接在Android中打开MyPlugTest2\platforms\android\app
$ cordova run android

achievement

Open the MyPlugTest2\platforms\android\app folder in Android Studio to debug the project. The final result is as follows:
Please add a picture description
Please add a picture description
Please add a picture description

reference:

Cordova plug-in development is enough

Cordova plug-in use and development study notes

Create your own cordova plugin using plugman

appendix

source code

Guess you like

Origin blog.csdn.net/m0_47420894/article/details/123999665