插件介绍

之前对 Ionic 3 项目插件的结构做过简单的介绍Ionic 3 插件应用:plugin基本知识了解

一个插件应该至少包含以下file:
plugin-name
————————-src //插件支持平台
———android.java //添加了支持Android平台
————————-www //JS文件,将Cordova.exec方法暴露给HTML/JS调用
———android.js
————————-plugin.xml //插件的配置文件,通知CLI哪个平台应该从什么地方Copy哪些文件到什么地方,以及CLI在生成config.xml时应该根据平台加入什么样的特殊设置

在自定插件时,我们可以按照上述的目录结构,建立各自的文件,但是这样做的话,比较繁琐,因此一般不推荐这样做。

推荐使用插件生成工具plugman,他会自动帮我们创建好想要的插件目录,然后去对应文件中实现我们需要的功能即可。

安装plugman

  1. $ npm install -g plugman

创建插件模板

plugman可用的命令

  1. plugman manages plugin.xml-compatible cordova plugins into cordova-generated projects.
  2. Usage
  3. =====
  4. To display this help file, use one of the following:
  5. $ plugman --help
  6. $ plugman -h
  7. To display the plugman version, use one of the following:
  8. $ plugman --version
  9. $ plugman -v
  10. Optional flags
  11. --------------
  12. --debug|-d : Verbose mode
  13. Install a plugin
  14. ----------------
  15. $ plugman install --platform <platform> --project <directory> --plugin <plugin> [--variable NAME=VALUE]
  16. Parameters:
  17. - platform <platform>: One of android, ios, blackberry10, wp8, or windows8
  18. - project <directory>: Path reference to a cordova-generated project of the platform you specify
  19. - plugin <plugin>: One of a path reference to a local copy of a plugin, or a remote https: or git: URL pointing to a cordova plugin (optionally append #branch:subdir) or
  20. a plugin ID from http://plugins.cordova.io
  21. - variable NAME=VALUE: Some plugins require install-time variables to be defined. These could be things like API keys/tokens or other app-specific variables.
  22. Optional parameters:
  23. - www <directory>: www assets for the plugin will be installed into this directory. Default is to install into the standard www directory for the platform specified
  24. - plugins_dir <directory>: a copy of the plugin will be stored in this directory. Default is to install into the <project directory>/plugins folder
  25. - searchpath <directory>: when looking up plugins by ID, look in this directory and each of its subdirectories for the plugin before hitting the registry.
  26. Multiple search paths can be used by either specifying the flag multiple times, or by separating paths with a delimiter (: on 'nix, ; on Windows).
  27. Uninstall a plugin
  28. ------------------
  29. $ plugman uninstall --platform <platform> --project <directory> --plugin <plugin-id>
  30. Parameters:
  31. - platform <platform>: One of android, ios, blackberry10, wp8, or windows8
  32. - project <directory>: Path reference to a cordova-generated project of the platform you specify
  33. - plugin <plugin-id>: The plugin to remove, identified by its id (see the plugin.xml's <plugin id> attribute)
  34. Interacting with the registry
  35. =============================
  36. NOTICE: The Cordova Plugin registry became read-only, so the following commands have been deprecated and removed:
  37. $ plugman adduser
  38. $ plugman publish
  39. $ plugman unpublish
  40. $ plugman owner add/rm
  41. For managing plugins for the npm registry, use corresponding npm commands. For more info on npm commands see `npm help <command>`.
  42. Learn more about publishing your plugins to npm at http://plugins.cordova.io/npm/developers.html
  43. Search for a plugin
  44. -------------------
  45. $ plugman search <keyword1 keyword2 ...>
  46. Display plugin information
  47. --------------------------
  48. $ plugman info <pluginID>
  49. Manage registry configuration
  50. -----------------------------
  51. Display current configuration settings:
  52. $ plugman config ls
  53. Display the current registry URL:
  54. $ plugman config get registry
  55. Set registry URL:
  56. $ plugman config set registry <url>
  57. Example:
  58. $ plugman config set registry http://localhost:5984/registry/_design/app/_rewrite
  59. Manage Owners
  60. -------------
  61. Plugin owners are allowed to publish updates to a plugin. To display a list of owners for a plugin, use:
  62. $ plugman owner ls <pluginID>
  63. Example:
  64. $ plugman owner ls org.apache.cordova.core.file
  65. Create A Plugin
  66. ---------------
  67. $ plugman create --name <pluginName> --plugin_id <pluginID> --plugin_version <version> [--path <directory>] [--variable NAME=VALUE]
  68. Parameters:
  69. - <pluginName>: The name of the plugin
  70. - <pluginID>: An ID for the plugin, ex: org.bar.foo
  71. - <version>: A version for the plugin, ex: 0.0.1
  72. - <directory>: An absolute or relative path for the directory where the plugin project will be created
  73. - variable NAME=VALUE: Extra variables such as description or Author
  74. Add a Package.JSON file to plugin
  75. ---------------------------------
  76. Creates a package.json file in the plugin based on values from plugin.xml.
  77. $ plugman createpackagejson <directory>
  78. Add a Platform to a Plugin
  79. --------------------------
  80. $ plugman platform add --platform_name <platform>
  81. Parameters:
  82. - <platform>: One of android, ios
  83. Remove a Platform from a Plugin
  84. -------------------------------
  85. $ plugman platform remove --platform_name <platform>
  86. Parameters:
  87. - <platform>: One of android, ios

使用创建插件的命令

  1. Create A Plugin
  2. ---------------
  3. $ plugman create --name <pluginName> --plugin_id <pluginID> --plugin_version <version> [--path <directory>] [--variable NAME=VALUE]
  4. Parameters:
  5. - <pluginName>: The name of the plugin
  6. - <pluginID>: An ID for the plugin, ex: org.bar.foo
  7. - <version>: A version for the plugin, ex: 0.0.1
  8. - <directory>: An absolute or relative path for the directory where the plugin project will be created
  9. - variable NAME=VALUE: Extra variables such as description or Author

对应的参数都有说明,此处不再进行翻译,开始创建一个插件模板(插件可以选择创建在任意目录)

  1. $ plugman create --name ZKCustomPlugin --plugin_id zhaikun68.plugin.custom --plugin_version 0.0.1 --path E:\zhaikun\MyPlugins --variable zhaikun68

打开创建的插件模块
Ionic 3 项目实战------自定义插件 - 图1

添加插件支持的平台

进入插件的根目录

支持Android

  1. $ plugman platform add --platform_name android

Ionic 3 项目实战------自定义插件 - 图2

支持iOS平台

  1. $ plugman platform add --platform_name ios

Ionic 3 项目实战------自定义插件 - 图3

plugin.xml文件内容说明

  1. <?xml version='1.0' encoding='utf-8'?>
  2. <!--插件的标识,即发布安装到 plugin ID ,在创建插件是设定-->
  3. <plugin id="zhaikun68.plugin.custom" version="0.0.1" xmlns="http://apache.org/cordova/ns/plugins/1.0"
  4. xmlns:android="http://schemas.android.com/apk/res/android">
  5. <!--插件的名称-->
  6. <name>ZKCustomPlugin</name>
  7. <ZHAIKUN68/>
  8. <!--对应我们的 javascript 文件,src 属性指向 www/ZKCustomPlugin.js-->
  9. <js-module name="ZKCustomPlugin" src="www/ZKCustomPlugin.js">
  10. <!--指定clobbers ,然后通过target的值来调用 ZKCustomPlugin.js,此处对应 ZKCustomPlugin.js exports的对象-->
  11. <clobbers target="cordova.plugins.ZKCustomPlugin"/>
  12. </js-module>
  13. <!--支持的平台Android-->
  14. <platform name="android">
  15. <config-file parent="/*"
  16. target="res/xml/config.xml"><!--这里是表示在res/xml/config.xml文件中插入以下一行代码-->
  17. <feature name="ZKCustomPlugin">
  18. <param name="android-package"
  19. value="zhaikun68.plugin.custom.ZKCustomPlugin"/><!--调用插件的类名,实现了execute方法-->
  20. </feature>
  21. </config-file>
  22. <config-file parent="/*" target="AndroidManifest.xml"/><!--对AndroidManifest.xml文件进行修改-->
  23. <!--表示将插件src/android目录下的ZKCustomPlugin.java文件拷贝到androidsrc/zhaikun68/plugin/custom目录下面去-->
  24. <!--如果有引用包,也可以这样拷贝到安卓的指定lib下面去-->
  25. <source-file src="src/android/ZKCustomPlugin.java" target-dir="src/zhaikun68/plugin/custom/ZKCustomPlugin"/>
  26. </platform>
  27. <!--支持的平台iOS-->
  28. <platform name="ios">
  29. <config-file parent="/*" target="config.xml">
  30. <feature name="ZKCustomPlugin">
  31. <param name="ios-package" value="ZKCustomPlugin"/>
  32. </feature>
  33. </config-file>
  34. <source-file src="src/ios/ZKCustomPlugin.m"/>
  35. </platform>
  36. </plugin>

ZKCustomPlugin.js文件内容说明

  1. var exec = require('cordova/exec');
  2. exports.coolMethod = function (arg0, success, error) {
  3. /**
  4. * Cordova.exec()方法说明
  5. * function(winParam) {}:成功回调函数。假设您的 exec成功完成,此功能将随您传递给它的任何参数一起执行
  6. * function(error) {}:错误回调函数。如果操作未成功完成,则此功能将执行可选的错误参数
  7. * "service":在本机端呼叫的服务名称,与原生端的类名保持一致
  8. * "action":在本机端调用的动作名称,对应原生类execute()的入参,原生代码通过对action进行判断,从而知道JS让原生端执行什么样的功能
  9. * [ arguments ]:传到原生环境的参数数组
  10. */
  11. exec(success, error, "ZKCustomPlugin", "coolMethod", [arg0]);
  12. };

ZKCustomPlugin.java文件内容说明

  1. package zhaikun68.plugin.custom;
  2. import org.apache.cordova.CordovaPlugin;
  3. import org.apache.cordova.CallbackContext;
  4. import org.json.JSONArray;
  5. import org.json.JSONException;
  6. import org.json.JSONObject;
  7. /**
  8. * This class echoes a string called from JavaScript.
  9. */
  10. public class ZKCustomPlugin extends CordovaPlugin {//必须继承CordovaPlugin
  11. /**
  12. * action对应exec传过来的action
  13. * args对应exec传过来的参数数组
  14. * callbackContext:对应exec传过来的回调函数
  15. */
  16. @Override
  17. public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
  18. if (action.equals("coolMethod")) {
  19. String message = args.getString(0);
  20. this.coolMethod(message, callbackContext);
  21. return true;
  22. }
  23. return false;
  24. }
  25. private void coolMethod(String message, CallbackContext callbackContext) {
  26. if (message != null && message.length() > 0) {
  27. callbackContext.success(message);//成功的回调函数
  28. } else {
  29. callbackContext.error("Expected one non-empty string argument.");//失败的回调函数
  30. }
  31. }
  32. }

将自定义的插件添加到我们创建的项目

  1. $ ionic cordova plugin add E:\zhaikun\MyPlugins\ZKCustomPlugin

未添加成功,有错误信息提示

  1. $ > cordova plugin add E:\zhaikun\MyPlugins\ZKCustomPlugin --save
  2. × Running command - failed!
  3. [ERROR] An error occurred while running cordova plugin add E:\zhaikun\MyPlugins\ZKCustomPlugin --save (exit code 1):
  4. Error: Invalid Plugin! E:\zhaikun\MyPlugins\ZKCustomPlugin needs a valid package.json

错误信息翻译过来大概就是:插件的根目录下需要一个package.json文件
记性好的大牛应该发现了在 plugman 工具中,正好有创建package.json文件的命令

  1. Add a Package.JSON file to plugin
  2. ---------------------------------
  3. Creates a package.json file in the plugin based on values from plugin.xml.
  4. $ plugman createpackagejson <directory>

创建package.json文件(进入插件的根目录)

  1. $ plugman createpackagejson E:\zhaikun\MyPlugins\ZKCustomPlugin

回车后会提示输入插件名、版本号、插件描述、git仓库地址、作者和证书信息,如果不进行修改,一直回车即可
Ionic 3 项目实战------自定义插件 - 图4
回到我们项目的根目录,重新添加插件

  1. $ ionic cordova plugin add E:\zhaikun\MyPlugins\ZKCustomPlugin

Ionic 3 项目实战------自定义插件 - 图5

插件调用

在home.html文件中增加两个按钮

  1. <ion-header>
  2. <ion-navbar>
  3. <ion-title>Home</ion-title>
  4. </ion-navbar>
  5. </ion-header>
  6. <ion-content padding>
  7. <h2>Welcome to Ionic!</h2>
  8. <p>
  9. This starter project comes with simple tabs-based layout for apps
  10. that are going to primarily use a Tabbed UI.
  11. </p>
  12. <p>
  13. Take a look at the <code>src/pages/</code> directory to add or change tabs,
  14. update any existing page or create new pages.
  15. </p>
  16. <!--这里是添加的两个按钮-->
  17. <button ion-button (click)="getNativeSuccess()">模拟-成功调用原生插件</button>
  18. <button ion-button (click)="getNativeFailed()">模拟-失败调用原生插件</button>
  19. </ion-content>

然后修改home.ts文件中的内容

  1. import {Component} from '@angular/core';
  2. import {NavController} from 'ionic-angular';
  3. declare let cordova: any;//这里是修改的代码
  4. @Component({
  5. selector: 'page-home',
  6. templateUrl: 'home.html'
  7. })
  8. export class HomePage {
  9. constructor(public navCtrl: NavController) {
  10. }
  11. //这里是修改的代码
  12. getNativeSuccess() {
  13. cordova.plugins.ZKCustomPlugin.coolMethod(
  14. '原生插件调用成功',
  15. successMsg => {
  16. alert(successMsg)
  17. }, failedMsg => {
  18. alert(failedMsg)
  19. }
  20. );
  21. }
  22. //这里是修改的代码
  23. getNativeFailed() {
  24. cordova.plugins.ZKCustomPlugin.coolMethod(
  25. '',
  26. successMsg => {
  27. alert(successMsg)
  28. }, failedMsg => {
  29. alert(failedMsg)
  30. }
  31. );
  32. }
  33. }

然后编译项目即可

  1. $ ionic cordova build android

效果图
Ionic 3 项目实战------自定义插件 - 图6
Ionic 3 项目实战------自定义插件 - 图7
Ionic 3 项目实战------自定义插件 - 图8
此处的调试是在真机上进行的,在浏览器调试会出现运行时异常
此外,插件一旦添加到项目中,以后如需对插件进行升级,需先卸载掉原先的插件,在重新安装