Writing Phonegap plugin for Android

Posted By : Ravi Sharma | 29-Oct-2013

PhoneGap plugin is a smart way to extend the existing PhoneGap functionality to add your own custom features via exposing native code.

One would wonder why the need for such plugins?

Answer is simple PhoneGap doesnot provide api's for few things which OS may allow. Many developers may have run into such a situation.

For instance, Social Media app ( Facebook, LinkedIn Integration ) , Display advertisments, bluetooth connectivity, send mail and list goes on.

In such cases you can always take help of native code to get the job done.

The plugins are able to communicate via a bridge between the JavaScript and native code. For Android, you write your native plugin code in Java and for iOS you write it in Objective-C.

This blog solely aims at writing PhoneGap plugin for Android.

Here you will learn how to generate alert as well as toast to display name entered in textbox.

Plugin will consist of at least a single Java class that extends the Plugin class. A plugin must have a method called execute that must return a PluginResult object. In addition to this, there is a best practice that the plugin should handle pause and resume events, and should handle message passing between plugins.

Plugin Class Mapping

The JavaScript portion of a plugin always uses the cordova.exec method as follows:

exec(<successFunction>, <failFunction>, <service>, <action>, [<args>]);

The code is in plugin.js file

 

	window.alertBack = function(str, callback) {

	 cordova.exec(callback, function(err) {

	 callback('Nothing to echo.');

	 }, "AlertBack", "alertBack", [str]);

	};

	

	

	function callback(arg){

	    alert(arg);

	}



AlertBack is our Service class , alertBack is action method.

Also map the class full path name in config.xml ( res-> xml->config.xml)

Here is the code for that.



    Hello Cordova
    
        A sample Apache Cordova application that responds to the deviceready event.
    
    
        Apache Cordova Team
    
    
    
    
    
        
    Writing an Android Java Plugin

Here is the AlertBack service-
    
    
    
    
    
    

 

Writing an Android Java Plugin

Here is the AlertBack service-

 

	@Override

	public boolean execute(String action, JSONArray args,

	CallbackContext callbackContext) throws JSONException {

	if (action.equals("alertBack")) {

	 Toast.makeText(cordova.getActivity(), "Using Toast You Entered "+

	 args.getString(0), Toast.LENGTH_LONG).show();

	            callbackContext.success("Returning from native You Entered "

	                    + args.getString(0));

	            return true;

	        }

	        return false; // Returning false results in a "MethodNotFound" error.

	    }

	

	    

	

	}

Essentially we compare the value of the action parameter, and dispatch the request off to a (private) method in the class, optionally passing some of the parameters to the method.

When catching exceptions and returning errors, it's important that the error we return to JavaScript match the Java exception as much as possible, for clarity.

Here we are checking action named alertBack, simply generating Toast for argument passed and Alert as well.

The code for alert is in main.js  

 

	function onLoad() {

	 document.addEventListener("deviceready", onDeviceReady, false);

	}

	

	    // device APIs are available

	    //

	function onDeviceReady() {

	    navigator.splashscreen.hide();

	}

	

	function clickButton1() {

	var userName = document.getElementById('userName').value;

	window.alertBack(userName, function(echoValue) {

	alert(echoValue);

	 });

		

	}

	

	function alertDismissed() {

	 // do something

	}

The MainActivity loads the html file.


public class MainActivity extends CordovaActivity 
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        super.init();
		super.loadUrl(Config.getStartUrl(),50000);
    }
    
    
    
   }


Here is the output

You may download code from here

 

Download Code

Thanks,

Ravi Sharma

[email protected]

About Author

Author Image
Ravi Sharma

Ravi Sharma is an Android application developer with experience in Java , Titanium and Phonegap frameworks. Ravi loves drawing and PC games.

Request for Proposal

Name is required

Comment is required

Sending message..