General Programming Toggle

[Cordova] Android Native Plugin Development

Echo Android Plugin Example

To match the JavaScript interface’s echo feature described in Application Plugins, use the plugin.xml to inject a featurespecification to the local platform’s config.xml file:

package org.apache.cordova.plugin;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

* This class echoes a string called from JavaScript.
public class Echo extends CordovaPlugin {
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) {
 } else {
 callbackContext.error("Expected one non-empty string argument.");

Then add the following to the src/org/apache/cordova/plugin/ file:

  <platform name="android">
        <config-file target="config.xml" parent="/*">
            <feature name="Echo">
                <param name="android-package" value="org.apache.cordova.plugin.Echo"/>

The necessary imports at the top of the file extends the class from CordovaPlugin, whose execute() method it overrides to receive messages from exec(). The execute() method first tests the value of action, for which in this case there is only one valid echo value. Any other action returns false and results in an INVALID_ACTION error, which translates to an error callback invoked on the JavaScript side.

Next, the method retrieves the echo string using the args object’s getString method, specifying the first parameter passed to the method. After the value is passed to a private echo method, it is parameter-checked to make sure it is not null or an empty string, in which case callbackContext.error() invokes JavaScript’s error callback. If the various checks pass, the callbackContext.success() passes the original message string back to JavaScript’s success callback as a parameter.


How to Use

exec(<successFunction>, <failFunction>, <service>, <action>, [<args>]);
cordova.exec( function(param) {}, function(error) {}, “MyPlugin”, “MyAction”, [“param1”, “param2”, “param3”]);

Leave a Reply