cordova跨平臺app開發02_自定義插件開發與安裝
視頻地址:http://t.cn/RacmXiy
cordova的自定義插件由js、原生代碼文件(java、oc)、plugin.xml三部分組成。
cordvoa提供了命令來創建插件模版項目。
創建插件模版
1. pluman的安裝
npm install –g plugman
2. 在d:\cordovaplugins創建一個名稱為helloplugins,id為com.zql. helloplugins,版本號為1.0.0的插件
cd D:\cordovaplugins
plugman create --name helloplugins --plugin_id com.zql.helloplugins --plugin_version 1.0.0
給插件增加android 平臺
cd helloplugins
plugman platform add --platform_name android
給插件增加ios平臺
plugman platform add --platform_name ios
插件模版目錄結構
src 目錄為原生代碼文件
www 為前臺js
plugin.xml為插件配置文件
模版代碼創建完成後,還需要修改
1 修改plugin.xml
1.1 修改js-module配置。clobbers配置了調用js方法的對象。cordova.plugins.helloplugins太長了調用起來太麻煩,修改為helloplugins
<js-module name="helloplugins" src="www/helloplugins.js">
<clobbers target="cordova.plugins.helloplugins"/>
</js-module>
<js-module name="helloplugins" src="www/helloplugins.js">
<clobbers target="helloplugins"/>
</js-module>
1.2 修改<platform name="android"></ platform>配置中的source-file。
將target-dir="src/com/zql//helloplugins"。修改為target-dir="src/ com/zql/plungins "。 com/zql/plungins為java文件的包名
插件開發
Js開發
一個插件可以配置多個js方法,通過exec的第四個參數來區分
var exec = require(‘cordova/exec‘);
var func1 = function(){};
func1.prototype.show = function(arg0, success, error) {
exec(success, error, "helloplugins", "show", arg0);
};
func1.prototype.show1 = function(arg0, success, error) {
exec(success, error, "helloplugins", "show1", arg0);
};
module.exports = new func1();
通過helloplugins.show(args,successcallback,errcallback);
helloplugins.show1(args,successcallback,errcallback);調用。
這裏的helloplugins為plugin.xml中js-model下的clobbers配置的值。
Andorid原生代碼開發
public class helloplugins extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("show")) {
String message = args.getString(0);
this.result(message, callbackContext);
return true;
}
if (action.equals("show1")) {
String message = args.getString(0);
this.result(message, callbackContext);
return true;
}
return false;
}
private void result(String message, CallbackContext callbackContext) {
if (message != null && message.length() > 0) {
callbackContext.success(message);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}
}
繼承了 CordovaPlugin 類,並重寫 execute
方法,使用 action 來判斷我們在 javascript 中調用的方法名,成功的話調用callbackContext.success(message)
,失敗調用 callbackContext.error(message)
方法,分別對應 javascript 文件中的success
和 error
回調函數。
插件的安裝
復制插件文件夾到項目跟目錄
cd 項目路徑
cordova plugin addhelloplugins
插件刪除
cd 項目路徑
cordova plugin rm插件id
cordova跨平臺app開發02_自定義插件開發與安裝