创建一个基本的自定义Cordova插件

时间:2015-12-17 09:31:28

标签: java android angularjs cordova-plugins

我是cordova和android原生代码的新手

我使用plugman创建了自己的插件。

plugman create --name myCustomPlugin --plugin_id myCustomPlugin --plugin_version 1.0

plugman为我开始生成了所有需要的文件。

js file www/myCustomPlugin.js

var exec = require('cordova/exec');

exports.coolMethod = function(arg0, success, error) {
  exec(success, error, "myCustomPlugin", "coolMethod", [arg0]);
};

java文件src/android/myCustomPlugin.java,方法执行

@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.");
    }
}  

问题是: 在cordova项目的js文件中。我如何调用myCustomPlugin?我怎么知道它有效?

我在我的cordova项目中使用角度,假设我的控制器是这样的:

.controller('mainCtrl', function($scope){
     // how to call myCustomPlugin here?
});

我的动机只是学习如何调用以及如何调用它,可能在点击它之后会执行本机警报或打开本机视图等。

提前致谢!

1 个答案:

答案 0 :(得分:1)

你可以这样做:

<强> WWW / myCustomPlugin.js

var MyCustomPlugin {
    coolMethod : function(arg0, success, error) {
        exec(success, error, "myCustomPlugin", "coolMethod", [arg0]);
    }
}

module.exports = MyCustomPlugin

在你的js客户端中:

MyCustomPlugin.coolMethod("Arg1", function(){}, function(){});

Cordova将为您注入JavaScript文件。

希望它有所帮助。