Develop native Android cordova plugins (basic)

If the cordova application needs to call the native Android interface, the method is to use the cordova plug-in. Cordova officially provides plug-ins with mainstream native functions, but if it cannot meet the needs, you can also develop the cordova plug-in by yourself.

 

The following describes the development of a simplest plug-in, the function is to call the native toast pop-up information

 

First create a new project with as to write the code for the plugin

PS: One of the pits in the development of cordova plug-ins is that there is no good coding environment, and even all class files of the plug-in must be manually added to the configuration file, which will be experienced later

 

The project name is plug1, and the package name should be written backwards

Add empry activity by default

After the configuration is completed, wait for a period of time. After the progress bar disappears, build it. If no error is reported, it means success.

 

Create a package named org.apache.cordova, the steps are as follows:

 

Back to capp1, you can see that there is the org.apache.cordova package, copy all the files under this package to the newly created package in the previous step, the purpose is to let plug1 have the class of cordova (so that the cordova plug-in can be developed)

 

After copying effect map

The plug1 project coded for developing cordova plug-ins has been established here. If there are multiple plug-in development in the future, this project can be reused

This project is not necessary (because the final compilation is not here), it can theoretically be coded in Notepad

 

Then start the coding of the plugin, first create a new package com.cesc.ewater.cordovaPlugin

 

Create a new class ToastPlugin, which is provided below and can be copied directly

package com.cesc.ewater.cordovaPlugin;

 

import android.widget.Toast;

 

import org.apache.cordova.CallbackContext;

import org.apache.cordova.CordovaArgs;

import org.apache.cordova.CordovaPlugin;

import org.apache.cordova.PluginResult;

import org.json.JSONArray;

import org.json.JSONException;

 

/**

 * Toast plugin

 */

public class ToastPlugin extends CordovaPlugin {

    @Override

    public boolean execute(String action, String rawArgs, CallbackContext callbackContext) throws JSONException {

        return super.execute(action, rawArgs, callbackContext);

    }

 

    @Override

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

        return super.execute(action, args, callbackContext);

    }

 

    /**

     * After js calls the plugin method, it will enter this method

     *

     * @param action The method name of the plugin, if a plugin has multiple methods, it is distinguished by this value

     * @param args The parameters passed in by js are used to pass values ​​to the plug-in outside the plug-in, array type, multiple parameters can be passed in

     * @param callbackContext The callback context used when calling back into JavaScript.

     * @return Whether the plugin is executed normally, bool type. It will also affect the callback called by js. If it is true, the success callback will be executed, and if it is false, the fail callback will be executed.

     * @throws JSONException

     */

    @Override

    public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {

        // Determine which method to call by action

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

            //Here you can implement some of your native logic functions

            //args.getString(0) means to read the first incoming parameter, and the type is string

            Toast.makeText(cordova.getActivity(), args.getString(0), Toast.LENGTH_SHORT).show();

 

            //The realization of the value returned by the plugin to the external js, the parameter 1 of the PluginResult constructor represents the execution result state, and the parameter 2 is the returned value

            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "The value returned by the plugin");

            pluginResult.setKeepCallback(true);

            callbackContext.sendPluginResult(pluginResult);

            return true;

        }

        return false;

    }

}

 

final effect

 

then go back to capp1

 

First install plugman with npm (global installation), the command is as follows: npm install -g plugman, there is no screenshot here

PS: Just install it on the first use

 

Enter the capp1 directory from the command line, and execute the following command to create a plugin. The plugin is named toast-plugin

plugman create --name toast-plugin --plugin_id toast-plugin --plugin_version 1.0.0

PS: where --name is followed by the plugin name, --plugin_id is followed by the plugin id, and --plugin_version is followed by the version

 

Generate this directory after success

 

In this directory, create a new folder android

 

Copy the ToastPlugin class file just edited in plug1 to the android folder

PS: In principle, all files of this plugin should be placed in this directory. In this example, only one file is copied because the plugin in this example does have only one class file, which is very simple.

PS: The directory structure of the files in this directory does not need to match the package. All files can be placed in the root directory, because there will be configuration file configuration class files and package names later.

 

Then start editing plugin.xml

Modify it to the following content (the full text content can be copied directly)

<?xml version='1.0' encoding='utf-8'?>

<plugin id="toast-plugin" version="1.0.0" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">

    <!--Plugin name-->

       <name>toast-plugin</name>

       <!--js part configuration -->

    <js-module name="ToastPlugin" src="www/toast-plugin.js">

              <!--Object name called by js-->

        <clobbers target="ToastPlugin" />

    </js-module>

      

       <!--Add Android platform-->

    <platform name="android">

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

                     <!--Object name called by js-->

            <feature name="ToastPlugin">

                            <!-- value=java class name full path-->

                <param name="android-package" value="com.cesc.ewater.cordovaPlugin.ToastPlugin"/>

            </feature> 

        </config-file> 

              <!-- src: The path of the java source file, target-dir: After the plugin is installed, the location of the source file should correspond to the package name above -->

        <source-file src="src/android/ToastPlugin.java" target-dir="src/com/cesc/ewater/cordovaPlugin" />         

    </platform>

</plugin>

 

PS: The detailed description of this file can also be skipped first

 

This file is the object that the plugin injects into js, ​​and the root directory is in the plugin directory

 

These are the object names of the js calling plugin, which should be the same

 

All files of the plugin (including class files, layout xml files, referenced jar package files, etc.) must be configured here

plugin.xml description ends here

 

Then start editing this file

The content is as follows, which can be copied directly into it,

var exec = require('cordova/exec');

 

//A exports.XXX represents a method of the plug-in. The parameter 4 after exports and the exec method is the method name (in this case, showToast)

var exec = require('cordova/exec');

 

//A exports.XXX represents a method of the plug-in. The parameter 4 after exports and the exec method is the method name (in this case, showToast)

exports.showToast = function (arg0, success, error) {

       //Parameter 1 and parameter 2 are the callback methods (js) for the success and failure of calling the plugin respectively.

       //parameter 3 is the plugin name

       //parameter 4 is the method name

       //parameter 5 is the parameter of js

    exec(success, error, 'ToastPlugin', 'showToast', [arg0]);

};

 

Open the console, enter the plugin directory, and execute npm init

 There are many input items in the middle, just press Enter, the effect is successful

 

After completion, there is a package.json file in the plugin directory, and start editing it

 

Add this section with text below

PS: id is the plugin name

    "cordova": {

    "id": "toast-plugin",

    "platforms": [

      "android"

    ]

  },

 

This is the end of the plugin modification, start adding the plugin to the cordova application

 

Go to the Android platform directory of capp1 in the console, enter the following command cordova plugin add E:\project\201712cordovaTest\code\capp1\toast-plugin, the path in the command is the directory of the plugin

PS: This command means to add the plug-in of a directory to the cordova application of capp1

successful effect

After success, capp1 will have the following files, you can see the ToastPlugin.java class file of the plugin

 

At this point, add the plugin to the cordova application

 

Next, start to modify the h5 application code, and use js to call the plug-in in the h5 application

 

Open the forgotten vue1

Find the js file of the home page

Add code: ToastPlugin.showToast("hello world");

It means to call the showToast method of the plugin named ToastPlugin and pass in the parameter "hello world"

 

After modifying the code, npm build it

PS: Starting from this operation, it has been explained in the previous use of cordova to package the h5 application into apk, that is, after the h5 application is modified, it is packaged into apk through a series of operations, but it is repeated here.

 

Open www (open with webstrom, as I said before), copy the file just generated

PS: Note that the files generated by each build will have a bunch of random numbers. If the random numbers change, it means that the content of the file has been modified, so it is regenerated. Otherwise, it will not change.

 

Then modify the file name of the referenced file in the indel.html file

 

Then start cordova to package apk, enter the directory of capp1 from the command line, and run the command cordova build android

After the build is successful, go back to capp1, plug in the phone, and start debugging

 

If successful, click the [Function 1] button in the upper left corner, and the message "hello world" will pop up

 

Additional chapters:

How to make the modification take effect after the plugin is modified:

Suppose you add 123 to the pop-up text content

 

After the code is modified, the console enters the capp1 directory and executes the command: cordova plugin rm toast-plugin, which means to delete the plugin

 

Then execute the command to add the plugin

After success, click as build of capp1, and then run it to see the modified effect

 

PS: Although there is a command cordova plugin update xxx for plugin update, it was found to be invalid after using it, so it can only be deleted and added

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325946081&siteId=291194637