ionic3使用cordova建立自定義插件

1 安裝 plugman 插件javascript

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

2 新建組件html

新建一個插件文件夾,進入插件文件夾。例如新建Plugins文件夾,而後執行下面語句java

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

說明:android

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

執行上述命令後會在Plugins文件夾下生成一個TestPlugin文件夾,而且TestPlugin文件夾內包含以下內容:ios

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

3 生成平臺(android/ios)插件代碼git

進入插件的根目錄,而後執行建立android或者ios的平臺支持命令apache

cd TestPlugin
plugman platform add --platform_name android

命令執行後在TestPlugin/src目錄下出現了android目錄,而且多了一個TestPlugin.java文件,打開TestPlugin.java文件,npm

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.
 */
//自定義插件須要繼承類,而且覆蓋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."); } } }CordovaPlugin

而且在www文件夾下也新生成TestPlugin.js,TestPlugin.js的做用是經過js暴露插件的功能給ionicjson

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:\work\ionic\plugins\TestPlugin>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:\work\ionic\plugins\TestPlugin\package.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:\work\ionic\plugins\TestPlugin>

標識紅色的地方,能夠自定義,也能夠直接回車選擇默認值。

而後會在插件根目錄下看到新建的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:\work\ionic\plugins\TestPlugin

會在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
相關文章
相關標籤/搜索