Search code examples
androidcordovaphonegap-pluginsnative-codecordova-plugins

Cordova Plugin for Native Android App


I am trying a cordova plugin to access the native android code.

plugin.xml

<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
    id="com.appgyver.plugin.Echo"
    version="1.0.0">

    <name>EchoPlugin</name>

  <description>
    Echo Plugin for Steroids.js
  </description>

  <asset src="www/EchoPlugin.js" target="plugins/EchoPlugin.js" />

  <engines>
    <engine name="cordova" version=">=2.7.0" />
  </engines>

  <!-- android -->
  <platform name="android">
    <config-file target="res/xml/config.xml" parent="plugins">
      <plugin name="Echo" value="com.appgyver.plugin.Echo"/>
    </config-file>

    <source-file src="src/android/com/appgyver/plugin/Echo.java"
      target-dir="src/org/apache/cordova/plugin" />
  </platform>

</plugin>

EchoPlugin.js

window.echo = function(str, callback) {
    cordova.exec(callback, function(err) {
        callback('Nothing to echo.');
    }, "Echo", "echo", [str]);
};

Echo.java

package com.appgyver.plugin;

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

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 {
    @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 am just trying to implement this plugin in a phone-gap project. But I don't know how to implement it. Do I need to create a separate folder for this plugin and then nest it under the plugins folder of my phone-gap project where the other plugins exist(inappbrowser,console,geolocation etc)? Please help me.

I have found many tutorials to write the cordova plugins but the problem is I don't know how to use these plugins within projects. Obviously this code has been copied from another site. But I want to test how exactly this one works. Please provide guidance.


Solution

  • check this. May be you would have missed adding in CORDOVA_PLUGIN.JS

    Please add and create separate folder for plugins for better code standard. Check this how to add in cordova_plugin.js

    How to add permissions to Android PhoneGap project?