Writing a PhoneGap or Cordova plugin to install it by command line

Posted By : Roopesh Sharma | 12-Jun-2014

Writing a PhoneGap or Cordova plugin to install it by command line

Plugin overview:

PhoneGap plugins are used to add functionality to our app which is hard in Phonegap using javascript code. In Phonegap, plugins are used to communicate between the JavaScript and native code. For Android, we write our plugin's code in Android(Java) for add or perform some functionalities, and for iOS, we write it in Objective-C (iOS native language).

Now, we take an example of a plugin for Android.

 

How Phonegap exposes native operating system functionality to JavaScript-based applications:

 

The JavaScript class call the native code using the Cordova.exec() function. When it calls Cordova.exec, it can pass in a success handler function which is executed in success case, an error handler function which is executed in failure case, and an array of arguments to be passed into native code, same reference to the native class's name and native function name. Cordova will handle the JavaScript-to-native communication, and we can used it in  our application.

 

Directory Structure of Cordova plugin:

 

plugin.xml file is at the top-level in directory. This file is used for installation of plugin. In src/ folder we have android and iOS folder to categorised our native code file. In android folder we have android native code and in ios we have ios native code. And the last www/ folder has the Plugin.js file. Plugin.js is file is used to implement the plugin's JavaScript interface which gives the facility call the native code in our app as per the reuirement.

 

plugin.xml

 


            


    Calendar Plugin
    Cordova Calendar Plugin
    Apache 2.0
    cordova,calendar

    
	
    
    
    
        
    

    
    
        
            
            
        
        
        
    
    
    
        

In plugin.xml file we have The plugin element is the plugin manifest's top-level element. It features the following attributes:

xmlns : The plugin namespace, http://apache.org/cordova/ns/plugins/1.0. If the document contains XML from other namespaces, such as tags to be added to the AndroidManifest.xml file, those namespaces should also be included in the top-level element.

xmlns:android=“http://schemas.android.com/apk/res/android" This is used for give the path of config.xml file.

id: A reverse-domain style identifier for the plugin, such as com.mobile.plugin version : This is used to describe the plugin version, such as 0.1.2

name: It is used to give the plugin name.

description: It is used to give the description about the plugin in human readable form.

keywords: It describe the keyword which is used by the plugin and it is separated by the comma.

engine: It specify versions of Apache Cordova-based frameworks that this plugin supports.

js-module: To add the javascript

platform:platform is used to define in which platform it is install. In this element we define all the platform related attributes is defined such as config-file target, source-file target etc.

 

Calendar.js

 

           var plugin = {
    createEvent: function(title, location, notes, startDate, endDate, successCallback, errorCallback) {
        cordova.exec(
            successCallback, // It is execute success callback function
            errorCallback, // It is execute error callback function
            'Plugin', // map our native Java class and called "Plugin"
            'addSchedule, // with this action name
            [{                  // and this array of custom arguments to create our entry
                "title": title,
                "detail": notes,
                "location": location,
                "startTime": startDate.getTime(),
                "endTime": endDate.getTime()
            }]
        ); 
    }
}     
        

Native Code:

Plugin.java

                package com.oodles.myplugin;
 
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.content.Intent;

public class Plugin extends CordovaPlugin {
    public static final String ACTION_ADD_SCHEDULE = "addSchedule";
}

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    try {
        if (ACTION_ADD_SCHEDULE.equals(action)) { 
        JSONObject arg_object = args.getJSONObject(0);
        Intent scheduleIntent = new Intent(Intent.ACTION_EDIT)
            .setType("vnd.android.cursor.item/event")
            .putExtra("beginTime", arg_object.getLong("startTime"))
            .putExtra("endTime", arg_object.getLong("endTime"))
            .putExtra("title", arg_object.getString("title"))
            .putExtra("detail", arg_object.getString("detail"))
            .putExtra("location", arg_object.getString("location"));
 
            this.cordova.getActivity().startActivity(scheduleIntent);
            callbackContext.success();
            return true;
        }
        callbackContext.error("Invalid action");
        return false;
    }
    catch(Exception e) {
        System.err.println("Exception: " + e.getMessage());
        callbackContext.error(e.getMessage());
        return false;
    } 
}
        

Now the Android(Java) native part of the plugin. This part is used for calling our native library and results back to JavaScript. The javascript our plugin is call the execute method. There we find which instruction to be executed for add a feature or perform some native specific task. In case of success Successful calls should result in callbackContext.success() and in case of failure or error unsuccessful calls should result in callbackContext.error(). In our library each library call is execute in a try-catch block which calls callbackContext.error() on an exception. In this library file first we define the package name to define where native code is stored and then import the required libraries to perform library specific task.

About Author

Author Image
Roopesh Sharma

Request for Proposal

Name is required

Comment is required

Sending message..