Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have created one java class which extends CordovaPlugin.

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.

How would I call this plugin from my javascript function? Please do the needful.

like image 596
Lavanya Avatar asked Oct 21 '22 15:10

Lavanya


1 Answers

You must first register your plugin in the config.xml in the res folder.

Then in the 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

like image 51
Alexis Avatar answered Nov 01 '22 08:11

Alexis