Simple steps to create phonegap 3.0 plugin for Android

Introduction:
Phonegap plugins allows us to customize the way to use the native features as per our need. Basically, the communication between JavaScript and native code is accomplished by the bridge provided by Phonegap.
Starting with the Android platform, to develop plugin, it follows some basic flow. We need to call cordova.exec() function in JavaScript, which will be mapped with our execute() method defined in our native java file. We can also pass useful parameters and can also define the success and error callback methods to trace the flow.

Description:
Here are three basic steps we need to flow to create the plugin.
1. Creating the Native Java Interface
2. Creating the JavaScript Interface
3. Configuring the plugin

Before going forward, i would like to bring the focus on the point that the plugin development for Phonegap 3.0 is now a bit different as compared to the previous versions, since the architecture has been changed and there are much difference in their working.

Let’s explore each steps in details.

Step #1 :  Creating the Native Java Interface

Create a java file “MyPlugin.java” and define the package name and import required java classes. The java file need to be in the src folder present in the root (MyDemoPlugin/src/android/MyPlugin.java).

package com.mindfire.plugin;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CallbackContext;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

Now define a class that extends the “CordovaPlugin” class and add the required static variables to denote different actions that our plugin will support in the public scope.

public class MyPlugin extends CordovaPlugin {
     public static final String ACTION_DEMO = "sampleAction";
}

Next add the execute() method along with the @Override annotation as this method is inherited from CordovaPlugin class.

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

}

Finally we need to add the below code inside the execute method to check the action passed and init the required activity. Then we need to call the success()/error() method of the CallbackContext class instance.

try {
    if (ACTION_DEMO.equals(action)) {
       JSONObject argObject = args.getJSONObject(0);

       // 'argObject' contains all the passed arguments. Use the getter method to grab them.
       // eg:  argObject.getString(“my-param”)

       // Here goes our custom code

       callbackContext.success();
       return true;
    }
    callbackContext.error("No such action defined");
    return false;
} catch(Exception e) {
    callbackContext.error(e.getMessage());
    return false;
}

Note: If we plan to have heavy duty plugin, then we may use multithreading concept. There are two ways,

// If our native code is interacting with the UI, then make it run on the main UI thread.
this.cordova.getActivity().runOnUiThread(new Runnable() {
     public void run() {

         // Here goes our custom code

         callbackContext.success();
     }
 }

OR

// If our native code is not interacting with the UI, then make it run on a separate thread.
this.cordova.getThreadPool().execute(new Runnable() {
    public void run() {

        // Here goes our custom code

        callbackContext.success();
    }
});

Step #2 : Creating the JavaScript Interface

Now our next step will be creating the JavaScript function that will call the cordova.exec() function.

var myPlugin = {
    runPlugin: function(successCallback, errorCallback, ) {
        cordova.exec(
	successCallback, // success callback function
	errorCallback, // error callback function
	'MyPlugin', // name of the native java class "MyPlugin"
	'demoAction', // name of the action to performed
	[{}]  // and this array of custom arguments to create our entry
        );
    }
};
module.exports = myPlugin;

Exporting the myPlugin variable will allow the use of it globally. The above code will be wrapped in myplugin.js which is present in www folder inside root.

Step #3 : Configuring the plugin

Finally we need to add one plugin.xml directly under the root. This file should contain some basic code like below,

<?xml version="1.0" encoding="UTF-8"?>

<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
           id="com.mindfire.plugin"
      version="0.1.0">
    <name>MyPlugin</name>
    <description>Demo Plugin</description>
    <license>Some value</license>
    <keywords>phonegap</keywords>

    <js-module src="www/myplugin.js" name="MyPlugin">
        <clobbers target="window.myplugin" />
    </js-module>

    <!-- android -->
    <platform name="android">
        <config-file target="res/xml/config.xml" parent="/*">
            <feature name="MyPlugin">
                <param name="android-package" value="com.mindfire.plugin.MyPlugin"/>
            </feature>
        </config-file>

        <source-file src="src/android/MyPlugin.java" target-dir="src/com/mindfire/plugin" />
     </platform>
</plugin>

Summary:
Finally, we will be having the following files with below structure.

www
    |_ myplugin.js
src
    |_ android
    |           |_ MyPlugin.java
    |
plugin.xml

That’s it. Now we are ready with our plugin.

Written ByAshis Kumar, Software Developer, Mindfire Solutions

Advertisements

4 thoughts on “Simple steps to create phonegap 3.0 plugin for Android

  1. Pingback: Simple steps to create phonegap 3.0 plugin for Android | MindfireMobile - appgong

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s