简体   繁体   English

如何从android中的javascript函数调用本机cordova插件?

[英]How to call native cordova plugin from javascript function in android?

I have created one java class which extends CordovaPlugin. 我创建了一个扩展CordovaPlugin的java类。

For eg, 例如,

public class SampleCardovaPlugin extends CordovaPlugin {
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("echo")) {
            String message = args.getString(0); 
            this.echo(message, callbackContext);
            return true;
        }
        return false;
    }
private void echo(String message, CallbackContext callbackContext) {
    if (message != null && message.length() > 0) { 
        callbackContext.success(message);
    } else {
        callbackContext.error("Expected one non-empty string argument.");
    }
}

} }

I'm using cordova2.5.0. 我正在使用cordova2.5.0。

How would I call this plugin from my javascript function? 我如何从我的javascript函数中调用此插件? Please do the needful. 请只做那些需要的。

You must first register your plugin in the config.xml in the res folder. 您必须首先在res文件夹的config.xml中注册您的插件。

Then in the javascript: 然后在javascript中:

cordova.exec(
    function(winParam) {},
    function(error) {},
    "service",
    "action",
    ["firstArgument", "secondArgument", 42, false]);

so in your case 所以在你的情况下

cordova.exec(
    function(data) { console.log(data);},
    function(error) { console.log(error);},
    "SampleCardovaPlugin",
    "echo",
    ["echo"]);

You must also be sure that the device is ready 您还必须确保设备已准备就绪

take a look at http://docs.phonegap.com/en/2.0.0/guide_plugin-development_index.md.html 看看http://docs.phonegap.com/en/2.0.0/guide_plugin-development_index.md.html

You have to create plugin (java class, package.json, plugin.xml ...) There is no easier way how to do it. 你必须创建插件 (java类,package.json,plugin.xml ...)没有更简单的方法来做到这一点。 But you can create really simple one (much easier then that one from documentation) -> read more here on my blog . 但你可以创建一个非常简单的(比文档中的那个更容易) - > 在我的博客上阅读更多内容

Then you call it in JS like this: 然后你在JS中调用它,如下所示:

cordova.exec(function(success) {},          //success callback
         function(error) {},                //error callback
         "Example",                         //class name
         "YOUR_ACTION_NAME_PARAMETER",      //action name 
         ["Dog", "Pig", 42, false]);        //args 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM