安裝插件
npm install -g plugman
創(chuàng)建目錄
plugman create --name EchoPlugin --plugin_id com.joker.cordova --plugin_version 1.0.0
創(chuàng)建成功后你將得到如下目錄:
plugin.xml
內(nèi)容
<?xml version='1.0' encoding='utf-8'?>
<plugin id="com.joker.cordova" version="1.0.0" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
<name>EchoPlugin</name>
<js-module name="EchoPlugin" src="www/EchoPlugin.js">
<clobbers target="cordova.plugins.EchoPlugin" />
</js-module>
</plugin>
id
為plugman創(chuàng)建命令使用的--plugin_id
version
為創(chuàng)建命令使用的--plugin_version
添加android平臺(插件)
cd EchoPlugin/
plugman platform add --platform_name android
執(zhí)行后你將得到如下目錄:
EchoPlugin為默認(rèn)插件跪呈,該插件返回調(diào)用的字符串參數(shù)凉敲。
EchoPlugin.java
為繼承CordovaPlugin
插件的類隅肥,主要內(nèi)容如下
public class EchoPlugin 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;
}
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.");
}
}
}
核心方法execute
執(zhí)行JS的調(diào)用
接收參數(shù):
action
調(diào)用方法名怜森,
args
調(diào)用方法傳遞的參數(shù)
callbackContext
異步回調(diào)函數(shù),向JS返回執(zhí)行結(jié)果
添加package.json
(插件安裝需要)
添加后目錄
package.json
內(nèi)容
{
"name": "cordova-plugin-echo",
"version": "1.0.0",
"description": "A sample Apache Cordova application that responds to the deviceready event.",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Apache Cordova Team",
"license": "Apache-2.0",
"cordova": {
"id": "cordova-plugin-echo",
"platforms": [
"android"
]
}
}
文件內(nèi)容根據(jù)自己使用調(diào)整
修改插件配置文件plugin.xml
plugin.xml
<?xml version='1.0' encoding='utf-8'?>
<plugin
id="cordova-plugin-echo"
version="1.0.0"
xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
<name>EchoPlugin</name>
<js-module name="EchoPlugin" src="www/EchoPlugin.js">
<clobbers target="EchoPlugin" />
</js-module>
<platform name="android">
<config-file parent="/*" target="res/xml/config.xml">
<feature name="EchoPlugin">
<param name="android-package" value="com.joker.cordova.EchoPlugin" />
</feature>
</config-file>
<config-file parent="/*" target="AndroidManifest.xml"></config-file>
<source-file src="src/android/EchoPlugin.java" target-dir="src/com/joker/cordova" />
</platform>
</plugin>
在Ionic中使用
安裝插件
cordova plugin add /Users/joker/Workspace/ionic/cordova/EchoPlugin
插件調(diào)用
cordova run android
順利的話在APP中可以看到alert的信息青伤。