首先有Ionic2以及Cordova环境
如果没有在命令行执行以下命令
npm install -g ionic cordova //全局安装ionic 和cordova指令
ionic start myApp tabs --v1 创建ionic2项目之前文章讲到了 “--v1&&--v2代表ionic不同版本”
npm install -g plugman //全局安装cordova插件命令
cordova platform add android //添加android平台 默认创建的项目只包含ios平台 其他的平台需要使用命令添加
现在基本基本开发环境已经就绪如果需要具体安装环境请跳转到Ionic2探索总结
首先我们查看一下plugman的帮助命令 直接输入plugman回车就能看到帮助,从帮助中找到下面这一句话
plugman create --name --plugin_id --plugin_version [--path ] [--variable NAME=VALUE]
这句话就是创建插件的命令,下面我给出一个创建的事例代码 最好是到刚才创建好的项目跟目录执行
plugman create --name bluetooths --plugin_id bluetooths --plugin_version 0.0.1
/*
[--path ]这个是可选的,如果你想创建到别的目录下的话可以通过这个可选的指定路径,如果仅仅想创建到当前路径下的话 可以省略这个可选的指令
*/
来看一下插件创建完毕后的目录以及文件
.
├── plugin.xml
├── src
└── www
└── bluetooths.js
这是当前的目录,然而感觉缺点什么?缺的是各平台的代码。我们再回头看看plugman这个命令的帮助 有这样的命令
Add a Platform to a Plugin
--------------------------
$ plugman platform add --platform_name
Parameters:
- : One of android, ios
Remove a Platform from a Plugin
-------------------------------
$ plugman platform remove --platform_name
Parameters:
- : One of android, ios
看到这应该就知道了 我们添加平台
cd bluetooths
plugman platform add --platform_name android
plugman platform add --platform_name ios
我们查看目录
.
├── plugin.xml
├── src
│ ├── android
│ │ └── bluetooths.java
│ └── ios
│ └── bluetooths.m
└── www
└── bluetooths.js
4 directories, 4 files
分析文件
plugin.xml
bluetooths @2
@3
@4
@5
@6
@7
1, 这个行指定了这个插件的id 版本
2, 插件名字
3, 4,5, 这个是插件的js部分 src说明js插件的文件的位置 target代表在怎么在全局中引用这个插件如果在es5中可以直接使用cordova.plugins.bluetooths这个对象上的各个方法,如果在es6以及typescript中使用的时候得先在代码的最上边加入这个
declare var cordova:any
...
cordova.plugins.bluetooths.function...
6, android平台的配置
7, ios平台的配置
bluetooths.js
var exec = require('cordova/exec'); //引入cordova内部已经实现与原生交互的接口
exports.coolMethod = function(arg0, success, error) {
exec(success, error, "bluetooths", "coolMethod", [arg0]);
};
上面三行代码实现了 导出一个名为coolMethod的方法 这个方法有三个参数 arg0为我们调用这个方法的时候参数,以及回调方法。
这个方法的内部是调用cordova插件的接口前两个是回调的方法,第三个是指定会响应到那个插件,第四个表面看是调用指定的方法,其实cordova插件的工作只是把coolMethod这个值传了过去(这个在android代码的时候说明) 以及后面的参数。
我们现在来看android的代码
public class bluetooths 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);