cordova與原生的交互都是基于插件的形式提供(例如躲查,獲取設(shè)備信息危虱、網(wǎng)絡(luò)狀態(tài)等)玖翅。依據(jù)項(xiàng)目業(yè)務(wù)就需要自定義插件
1.使用plugman創(chuàng)建MiPlugin插件脚曾,并安裝到項(xiàng)目中(會生成對應(yīng)的模板文件 plugin.xml MiPlugin.js MiPlugin.java 等文件)
1东且、安裝plugman
npm install -g plugman
2、創(chuàng)建插件
plugman create --name MiPlugin --plugin_id cordova-plugin-mi --plugin_version 1.0.0
cd MiPlugin
3. 增加Android平臺
plugman platform add --platform_name android
4. 生成package.json
npm init
5. 安裝本地插件
cordova plugin add 本地路徑
-
cordova plugin list
查看插件是否安裝成功
MiPlugin.js
在js文件添加hello
方法
var exec = require('cordova/exec');
// Reference name for the plugin
PLUGIN_NAME = 'MiPlugin';
// Plugin methods on the native side that can be called from JavaScript
pluginNativeMethod = {
COOLMETHOD: 'coolMethod',
HELLO : 'hello'
}
var MiPlugin = {
coolMethod : function (arg0, success, error) {
exec(success, error, PLUGIN_NAME, pluginNativeMethod.COOLMETHOD, [arg0]);
},
helloworld : function (arg0,success,error) {
exec(success, error, PLUGIN_NAME, pluginNativeMethod.HELLO, [arg0]);
}
}
module.exports = MiPlugin;
MiPlugin.java
在MiPlugin.java添加對應(yīng)的hello
方法
public class MiPlugin 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("hello")) {
this.jsHello(message,callbackContext);
}
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 jsHello(String message, CallbackContext callbackContext) {
System.out.println("hello world");
callbackContext.success();
}
}