ionic3使用cordova创建自定义插件

1 安装 plugman 插件

npm --registry https://registry.npm.taobao.org install -g plugman

2 新建组件

新建一个插件文件夹,进入插件文件夹。例如新建Plugins文件夹,然后执行下面语句

plugman create --name TestPlugin --plugin_id com.plugin.testPlugin --plugin_version 1.0.0

说明:

--name TestPlugin //自定义插件名称
--plugin_id com.plugin.testPlugin //自定义插件的包名
--plugin_version 1.0.0 //自定义插件版本

执行上述命令后会在Plugins文件夹下生成一个TestPlugin文件夹,并且TestPlugin文件夹内包含如下内容:

—TestPlugin
|——src
|——www
|——plugin.xml

3 生成平台(android/ios)插件代码

进入插件的根目录,然后执行创建android或者ios的平台支持命令

cd TestPlugin
plugman platform add --platform_name android

命令执行后在TestPlugin/src目录下出现了android目录,并且多了一个TestPlugin.java文件,打开TestPlugin.java文件,

package com.plugin.testPlugin;

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.
 */
//自定义插件需要继承CordovaPlugin类,并且覆盖execute方法。
public class TestPlugin extends CordovaPlugin {
   //参数action是用来判断执行哪个方法,args是json格式的参数,callbackContext响应返回结果。 @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; } 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."); } } }

并且在www文件夹下也新生成TestPlugin.js,TestPlugin.js的作用是通过js暴露插件的功能给ionic

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

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

说明:

TestPlugin //插件名称
coolMethod //方法名称

4 介绍plugin.xml

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

<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" id="com.plugin.testPlugin" version="1.0.0">
  <name>TestPlugin</name>
  <js-module name="TestPlugin" src="www/TestPlugin.js">
    <clobbers target="cordova.plugins.TestPlugin"/>
  </js-module>
  <platform name="android">
    <config-file parent="/*" target="res/xml/config.xml">
      <feature name="TestPlugin">
        <param name="android-package" value="com.plugin.testPlugin.TestPlugin"/>
      </feature>
    </config-file>
    <config-file parent="/*" target="AndroidManifest.xml"/>
    <source-file src="src/android/TestPlugin.java" target-dir="src/com/plugin/testPlugin/TestPlugin"/>
  </platform>
</plugin>

说明:

id: 插件的标识,即发布安装到plugin 的 ID
name:插件的名称
js-module:对应我们的 javascript 文件,src 属性指向 www/TestPlugin.js
platform:支持的平台,这里仅仅用到了 android

5 初始化package.json

在ionic3项目中添加插件,所添加的插件必须包含package.json文件,网上一些生成的方式尝试失败,最后发现执行下面命令可行。

npm init

例如下面执行过程

C:workionicpluginsTestPlugin>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (testplugin)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to C:workionicpluginsTestPluginpackage.json:

{
  "name": "testplugin",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this ok? (yes) yes

C:workionicpluginsTestPlugin>

标识红色的地方,可以自定义,也可以直接回车选择默认值。

然后会在插件根目录下看到新建的package.json文件

6 插件引入ionic3项目中

6.1 新建ionic3项目

ionic start TestIonic3 tabs
npm --registry https://registry.npm.taobao.org install
ionic serve

6.2 引入自定义插件

ionic cordova plugin add 你插件的存储路径

例如:

ionic cordova plugin add C:workionicpluginsTestPlugin

会在TestIonic3根目录下新增plugins目录,并生成相关配置文件和代码。

6.3 使用自定义插件

6.3.1 在home.html 上添加下面代码

<p>
    <button ion-button color="primary" (click)="callMyPlugin()">call my plugin</button>
</p>

6.3.2 修改home.ts代码

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
declare let cordova: any;
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController) {

  }
  callTestPlugin(){
    cordova.plugins.TestPlugin.coolMethod("今天好运气,一老狼请吃鸡呀!",result=>alert(result),error=>alert(error));
  }
}

标识红色的部分是定义cordova对象,和引用自定义插件方法

注意,这个变量的定义,是个全局的引用,表示所有的插件对象都加载进来

declare let cordova: any;

具体插件类的调用需要看被调用插件的配置文件plugin.xml中的节点

 <clobbers target="cordova.plugins.TestPlugin"/>

如果这个节点被定义为

 <clobbers target="BaiduTTS"/>

那么在调用时直接这样写

BaiduTTS.XXX(xxxxx);//xxxx代表方法名或者参数

6.4 查看效果

自定义插件只在手机上有效果,浏览器上不能运行,如果运行的话会报ReferenceError: cordova is not defined的错误,所以只能生成apk并安装到手机上查看效果。生成apk,需要执行下面命令

ionic cordova platform add android
ionic cordova build androi

或者通过usb手机调试

ionic cordova run android -l -c

6.5 修改自定义插件

自定义插件修改后必须先删除插件,然后再安装插件才可生效。

1)ionic cordova plugin list 列出所有已安装的插件
2)ionic cordova  plugin remove com.plugin.testPlugin 从ionic3项目中删除插件
3)ionic cordova plugin add 自定义插件路径 安装插件到ionic3项目

执行顺序为1->2->修改代码->3

例如在插件中增加一个方法,首先修改TestPlugin/Android/TestPlugin.java

package com.plugin.testPlugin;

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 TestPlugin 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("plus")) {//主方法中增加一段方法名称判断和调用的代码
            int x = args.getInt(0);
            int y = args.getInt(1);
            this.plus(x, y, callbackContext);
            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.");
        }
    }

    //新增一个传入两个参数求和的方法
    private void plus(int x, int y, CallbackContext callbackContext) {
        callbackContext.success(x + y);
    }
}

 修改TestPlugin/www/TestPlugin.js代码

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

var testAPI = {}

testAPI.coolMethod = function(arg0, success, error) {
    exec(success, error, "TestPlugin", "coolMethod", [arg0]);
};
//求和方法
testAPI.plus = function(arg0,arg1, success, error) {
    exec(success, error, "TestPlugin", "plus", [arg0,arg1]);
};

module.exports = testAPI;

修改自定义插件package.json和plugin.xml文件的版本号

修改ionic项目home.html代码,增加一个button

 <p>
    <button ion-button color="primary" (click)="callTestPluginNew()">new plus function</button>
  </p>

修改home.ts代码,增加一个调用方法

  callTestPluginNew(){
    cordova.plugins.TestPlugin.plus(3,7,result=>alert(result),error=>alert(error));
  }

重新添加自定义插件后,再次重新生成apk,查看效果

ionic cordova build android
原文地址:https://www.cnblogs.com/smartsensor/p/7904254.html