2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android

1/10 iki.phonegap.com//page/36753494/Ho to Create a PhoneGap Plugin for Android
phonegap
Wiki Page & File
VIEW
EDIT
Page history
Search this orkspace
How to Create a PhoneGap PIugin for Android
last edited by Tim Walsh 3 months ago

1. Introduction
2. Plugin Idea
3. Download Source Code
4. Creating PhoneGap Plugin Project
i. Create an Android Project
ii. Include PhoneGap Dependencies
iii. Implement Plugin Class
iv. Implement Plugin JavaScript
v. Write TestCase for the Plugin
vi. Test the plugin

lntroduction

This is a Step by Step Tutorial for Android PhoneGap Plugin. If you are new to PhoneGap please refer to
this documentation. Incase you are new the concept of PhoneGap Plugin, please refer to this
documentation.

PIugin ldea

PhoneGap provides an API to read and write file, however it does not provide a api to list files. We will
build a PhoneGap Plugin named DirectoryListingPlugin which helps us read contents of say SDCARD on
Android. This is shown in the video below.


To join this workspace, create an
account.
Already have an account? Log in!
Navigator
How To
Pages No Files

How to Create a PhoneGap Plugin for Andr
How To Create a PhoneGap Plugin for BlackBerry
How to Create a PhoneGap Plugin for iOS
How to Debug a PhoneGap Plugin for BlackBerry
How to Install a PhoneGap Plugin for Android
How to Install a PhoneGap Plugin for BlackBerry
SideBar
PhoneGap is a device independent framework
for web applications with native power.
Geolocation, accelerometer and more from your
device.

More info at PhoneGap.com

Recent Activity
PhoneGap Ajax Sample
edited by DarkwaveMD
FrontPage
edited by zhoucn9999
FrontPage
edited by JuliaStanley
File Transfer API to Mysql PHP coding
edited by gizmo
File Transfer API to Mysql PHP coding
edited by gizmo
File Transfer API to Mysql PHP coding
added by gizmo
HOW TO: Add admob ads to your phon
edited by Jeremy
More activity...

2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android
2/10 iki.phonegap.com//page/36753494/Ho to Create a PhoneGap Plugin for Android


DownIoad 5ource Code
Download the source code of the Tutorial here

Creating PhoneGap PIugin Project

Create an Android Project

2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android
3/10 iki.phonegap.com//page/36753494/Ho to Create a PhoneGap Plugin for Android


lncIude PhoneGap Dependencies

Refer to the PhoneGap Getting Started Documentation for this.

lmpIement PIugin CIass
2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android
4/10 iki.phonegap.com//page/36753494/Ho to Create a PhoneGap Plugin for Android
lmpIement PIugin CIass


2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android
5/10 iki.phonegap.com//page/36753494/Ho to Create a PhoneGap Plugin for Android

Add your implementation to execute method()
Here are the guidelines


1. action contains the action sent by the javascript. This can be used to do more than one action
when javascript calls this plugin. e.g for File Plugin, the action could be LIST,MKDIR,DELETE, etc
2. data is the arguments coming from JavaScript API to the native. This is an JSON Object. e.g for
File Plugin are filename,path,etc
3. callbackId - TBD
4. When Javascript calls the plugin it is a non blocking call. The javascript is notified back using
callbacks

CompIete 5ource Code


/**
* Example of Android PhoneGap Plugin
*/
package com.trial.phonegap.plugin.directorylisting;
import java.io.File;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import com.phonegap.api.PluginResult.Status;
/**
* PhoneGap plugin which can be involved in following manner from javascript
* <p>
* result example - {"filename":"/sdcard","isdir":true,"children":[{"filename":"a.txt","isdir":false,{..]
* </p>
* <pre>
* {@code
* successCallback = function(result){
* //result is a json
*
*
* failureCallback = function(error){
* //error is error message
*
*
* DirectoryListing.list("/sdcard",
* successCallback
* failureCallback);
*
*
2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android
6/10 iki.phonegap.com//page/36753494/Ho to Create a PhoneGap Plugin for Android
*
* </pre>
* @author Rohit Ghatol
*
*/
public class DirectoryListPlugin extends Plugin {
/** List Action */
public static final String ACTION="list";
/*
* (non-Javadoc)
*
* @see com.phonegap.api.Plugin#execute(java.lang.String,
* org.json.JSONArray, java.lang.String)
*/
@Override
public PluginResult execute(String action, JSONArray data, String callbackId) {
Log.d("DirectoryListPlugin", "Plugin Called");
PluginResult result = null;
if (ACTION.equals(action)) {
try {
String fileName = data.getString(0);
JSONObject fileInfo = getDirectoryListing(new File(fileName));
Log.d("DirectoryListPlugin", "Returning "+ fileInfo.toString());
result = new PluginResult(Status.OK, fileInfo);
catch (JSONException jsonEx) {
Log.d("DirectoryListPlugin", "Got JSON Exception "+ jsonEx.getMessage());
result = new PluginResult(Status.JSON_EXCEPTION);

else {
result = new PluginResult(Status.INVALID_ACTION);
Log.d("DirectoryListPlugin", "Invalid action : "+action+" passed");

return result;

/**
* Gets the Directory listing for file, in JSON format
* @param file The file for which we want to do directory listing
* @return JSONObject representation of directory list.
* e.g {"filename":"/sdcard","isdir":true,"children":[{"filename":"a.txt","isdir":false,{..]
* @throws JSONException
*/
private JSONObject getDirectoryListing(File file) throws JSONException {
JSONObject fileInfo = new JSONObject();
fileInfo.put("filename", file.getName());
fileInfo.put("isdir", file.isDirectory());
if (file.isDirectory()) {
JSONArray children = new JSONArray();
fileInfo.put("children", children);
if (null != file.listFiles()) {
for (File child : file.listFiles()) {
children.put(getDirectoryListing(child));

return fileInfo;

lmpIement PIugin Java5cript

5teps

1. Create a file called directoryListing.js
2. In it create a class named DirectoryListing
3. Create a member function named list().
4. In list() function call PhoneGap.exec(<<successCallback>>,<<failureCallback>>,<<Plugin
2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android
7/10 iki.phonegap.com//page/36753494/Ho to Create a PhoneGap Plugin for Android
4. In list() function call PhoneGap.exec(<<successCallback>>,<<failureCallback>>,<<Plugin
Name>>,<<Action Name>>,<<Arguments Array>>);
5. Finally register both DirectoryListing class as an JavaScript Plugin and register Java Class as the
native Plugin (invoked from javascript)

/**
*
* @return Object literal singleton instance of DirectoryListing
*/
var DirectoryListing = function() {
;
/**
* @param directory The directory for which we want the listing
* @param successCallback The callback which will be called when directory listing is successful
* @param failureCallback The callback which will be called when directory listing encouters an error
*/
DirectoryListing.prototype.list = function(directory,successCallback, failureCallback) {
return PhoneGap.exec( successCallback, //Success callback from the plugin
failureCallback, //Error callback from the plugin
'DirectoryListPlugin', //Tell PhoneGap to run "DirectoryListingPlugin" Plugin
'list', //Tell plugin, which action we want to perform
[directory]); //Passing list of args to the plugin
;

PhoneGap.addConstructor(function() {
PhoneGap.addPlugin("directoryListing", ne DirectoryListing());
);


Note that prior to PhoneGap v1.0.0 the addConstructor function above also needed a line to
register the native (java) class with PhoneGap's plugin manager. Hence if you download the
sample code you will see this line included in the addConstructor function.

PluginManager.addService("DirectorListPlugin","com.trial.phonegap.plugin.directorlisting.DirectorListPlugin");
From version 1.0.0 the plugin manager was removed and replaced with the
res/ml/plugins.ml file. You need to add the following line to it:
<plugin name="DirectorListPlugin"
value=""com.trial.phonegap.plugin.directorlisting.DirectorListPlugin"/>
If you see a Failed o n conco: RefeenceEo: PlginManage i no definedwarning
its probably because you are on version 1.0.0 or higher and are still trying to use addService in
your Javascript constructor.


write TestCase for the PIugin
Coming Soon... (I am working on a strategy to use Selenium JavaScript to test phonegap)

Test the pIugin

In order to test the plugin, you need to create a dummy application which consumes the plugin.

This can be done by creating a standard PhoneGap application for Android and including either
the Java source code for your plugin or the JAR as well as the the JavaScript code.

The one thing to do when you are actually including a plugin in an application is that you need to
edit the /res/xml/plugins.xml file such that the JavaScript code can get access to the Java plugin
code. Add the following XML element as a child of the "plugins" element in the plugins.xml file:
<plugin name="DirectoryListPlugin" value="com.trial.phonegap.plugin.directorylisting.DirectoryListPlugin" />

In our case the resulting application is shown below:

2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android
8/10 iki.phonegap.com//page/36753494/Ho to Create a PhoneGap Plugin for Android

2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android
9/10 iki.phonegap.com//page/36753494/Ho to Create a PhoneGap Plugin for Android

CompIete 5ource Code

<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
</head>
<body>
<!-- Button -->
<input disabled id="list-sdcard" type="button" value="List SDCard Contents" />
<hr>

<!-- Place Holder for placing the SD Card Listing -->
<div id="result"></div>

<hr>

<script type="text/javascript" src="phonegap-1.0.0.js"></script>
<script type="text/javascript" src="directorylisting.js"></script>
<script type="text/javascript" >
document.addEventListener('deviceready', function() {
var btn = document.getElementById("list-sdcard");
btn.onclick = function() {
window.plugins.directoryListing.list( "/sdcard",
function(r){printResult(r),
function(e){console.log(e)
);

btn.disabled=false;
, true);


function printResult(fileInfo){
var innerHtmlText=getHtml(fileInfo);
document.getElementById("result").innerHTML=innerHtmlText;


function getHtml(fileInfo){
var htmlText="<ul><li>"+fileInfo.filename;
if(fileInfo.children){

for(var index=0;index<fileInfo.children.length;index++){
htmlText=htmlText+getHtml(fileInfo.children[index]);


htmlText=htmlText+"</li></ul>";
return htmlText;


2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android
10/10 iki.phonegap.com//page/36753494/Ho to Create a PhoneGap Plugin for Android
PDF version

</script>

</body>
</html>

Packaging the pIugin

JAR up your Java source code.

Create a ZIP file containing your JAR and JavaScript file.

That's it!

When people "install" your plugin it will be similar to the process that you used for testing the
plugin ... for now!

com/ /page/36753494/Ho to Create a PhoneGap Plugin for Android 2/10 .phonegap.2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android Do nload So ce Code Download the source code of the Tutorial here C ea ing PhoneGap Pl gin P ojec C ea e an And oid P ojec iki.

iki.phonegap.2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android Incl de PhoneGap Dependencie Refer to the PhoneGap Getting Started Documentation for this.com/ /page/36753494/Ho Implemen Pl gin Cla to Create a PhoneGap Plugin for Android 3/10 .

com/ /page/36753494/Ho to Create a PhoneGap Plugin for Android 4/10 .2/27/12 Implemen Pl gin Cla phonegap / Ho to Create a PhoneGap Plugin for Android iki.phonegap.

data is the arguments coming from JavaScript API to the native. mot o.oFl.hngpaiPuiRsl.p. This can be used to do more than one action when javascript calls this plugin.etc 3.p. The javascript is notified back using callbacks Comple e So ce Code /* * *Eapeo AdodPoea Pui xml f nri hnGp lgn * / pcaecmtilpoea. etc 2.SNxeto. e.hngppui.phonegap. When Javascript calls the plugin it is a non blocking call.lgneut mot o.ietrlsig ipr jv.TBD 4. akg o.snJOOjc.com/ /page/36753494/Ho to Create a PhoneGap Plugin for Android 5/10 .hngpaiPuiRsl.cide"["ieae:att. ipr adodui.g for File Plugin are filename.DELETE.x""si" *<p /> *<r> pe *{cd @oe *scesalak=fnto(eut{ ucsClbc ucinrsl) * /rsl i ajo /eut s sn * * *fiuealak=fnto(ro) alrClbc ucinerr{ * /erri errmsae /ro s ro esg * * *Drcoyitn.it"scr" ietrLsigls(/dad.tlLg ipr cmpoea.hngpaiPui.lgneutSau. * scesalak ucsClbc * fiuealak.o.lgndrcoyitn. the action could be LIST. This is an JSON Object. mot nri.ra.MKDIR.SNra.tts /* * *Poea pui wihcnb ivle i floigmne fo jvsrp hnGp lgn hc a e novd n olwn anr rm aacit *<> p *rsl eape-{flnm""scr""si"tu.snJOAry ipr ogjo. callbackId . e.ie ipr ogjo.SNbet mot r. ipr cmpoea. mot r.snJOEcpin ipr ogjo. mot r.idr:re"hlrn:{flnm"". mot aai. alrClbc) * * iki.g for File Plugin. ipr cmpoea.p.idr: eut xml "ieae:/dad.2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android Add your implementation to execute method() Here are the guidelines 1.lgn mot o.path. action contains the action sent by the javascript.

(Drcoyitlgn.u(eDrcoyitn(hl). cth(SNxeto joE){ ac JOEcpin snx Lgd"ietrLsPui" "o JO Ecpin" joE.(Drcoyitlgn.u(cide" cide) ienopt"hlrn. flIf. iegtae). 4.SNECPIN. o. eun eut /* * *Gt teDrcoylsigfrfl. lgneut eut ul i (CINeul(cin){ f ATO.<<Plugin iki.x""si"fle { *@hosJOEcpin trw SNxeto * / piaeJOOjc gtietrLsigFl fl)trw JOEcpin{ rvt SNbet eDrcoyitn(ie ie hos SNxeto JOOjc flIf =nwJOOjc(.eNm() ienopt"ieae.(Drcoyitlgn.SNra.u(flnm" fl.itie(){ o Fl hl ielsFls) cide.idr:as .2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android * *<pe /r> *@uhrRhtGao ato oi htl * * / pbi casDrcoyitlgnetnsPui { ulc ls ietrLsPui xed lgn /*Ls Ato * * it cin / pbi sai fnlSrn ATO=ls" ulc ttc ia tig CIN"it. / * *(o-aao) nnJvdc * *@e cmpoea.u(idr.NAI_CIN.<<failureCallback>>. Create a member function named list().cide"["ieae:att. Rtrig + ienotSrn() rsl =nwPuiRsl(ttsO.flIf) eut e lgneutSau.jv. Pui ald) PuiRsl rsl =nl. o. Create a file called directoryListing. Lgd"ietrLsPui" "nai ato :"ato+ pse".qasato) ty{ r Srn flNm =dt.tig *ogjo.fl.phonegap. "ieae:/dad. Gt SN xeto + snxgtesg() rsl =nwPuiRsl(ttsJO_XETO) eut e lgneutSau. hlrn.idr:re"hlrn:{flnm"". Ivld cin +cin" asd) rtr rsl.snJOAry aaln. i (ul! fl. se o.agSrn. rtr SNbet ersnain f ietr it * eg{flnm""scr""si"tu. flIf.itie(){ f nl = ielsFls) fr(iecid:fl.com/ /page/36753494/Ho to Create a PhoneGap Plugin for Android 6/10 .exec(<<successCallback>>. SNbet ieno e SNbet) flIf.eSrn() tig ieae aagttig0.JOArydt.agSrn) r.tig * / @vrie Oerd pbi PuiRsl eeueSrn ato.i JO fra es h ietr itn o ie n SN omt *@aa fl Tefl frwihw wn t d drcoylsig prm ie h ie o hc e at o o ietr itn *@eunJOOjc rpeetto o drcoyls. Lgd"ietrLsPui" "eunn " flIf.Srn clbcI){ ulc lgneut xct(tig cin SNra aa tig alakd Lgd"ietrLsPui" "lgnCle".(Drcoyitlgn. o. o. hlrnptgtietrLsigcid) rtr flIf. i (ieiDrcoy) { f fl.lgneeuejv.eMsae). .K ieno.p.sietr() JOArycide =nwJOAry) SNra hlrn e SNra(. eun ieno Implemen Pl gin Ja aSc ip S ep 1.js 2.otig).sietr() ienopt"si" ieiDrcoy). In list() function call PhoneGap. es { le rsl =nwPuiRsl(ttsIVLDATO) eut e lgneutSau. In it create a class named DirectoryListing 3.hngpaiPui#xct(aaln. JOOjc flIf =gtietrLsignwFl(ieae) SNbet ieno eDrcoyitn(e ieflNm).

ietrLsPui In our case the resulting application is shown below: iki.Director ListPlugin"/> If you see a Failed o n con c o : Refe enceE o : Pl ginManage i no defined warning its probably because you are on version 1.rttp. This can be done by creating a standard PhoneGap application for Android and including either the Java source code for your plugin or the JAR as well as the the JavaScript code. Hence if you download the sample code you will see this line included in the addConstructor function.ucsClbc.it=fnto(ietr.xml file such that the JavaScript code can get access to the Java plugin code.addService("Director ListPlugin". /el hnGp o u Drcoyi 'it.hngppui. you need to create a dummy application which consumes the plugin.phonegap. drcoy) /Psigls o ag t tepui /asn it f rs o h lgn .xml file: <lgnnm=Drcoyitlgn vle"o. ml file.trial.director listing.0 or higher and are still trying to use addService in your Javascript constructor. e ietrLsig).exec(<<successCallback>>. /Scesclbc fo tepui /ucs alak rm h lgn fiuealak alrClbc. /Errclbc fo tepui /ro alak rm h lgn 'ietrLsPui' /Tl Poea t rn"ietrL Drcoyitlgn.director listing.0.ra. From version 1.com/ /page/36753494/Ho to Create a PhoneGap Plugin for Android 7/10 . W i e Te Ca e fo Te he pl gin he Pl gin Coming Soon.fiuealak { ietrLsigpooyels ucindrcoyscesalak alrClbc) rtr Poea. 5. PluginManager.Director ListPlugin").0. In list() function call PhoneGap. Add the following XML element as a child of the "plugins" element in the plugins. The one thing to do when you are actually including a plugin in an application is that you need to edit the /res/xml/plugins.<<Plugin Name>>.phonegap.phonegap.ietrlsigDrcoyitlgn pui ae"ietrLsPui" au=cmtilpoea.plugin.trial. Poea.xc eun hnGpee( scesalak ucsClbc.dPui(drcoyitn" n Drcoyitn() hnGpadlgn"ietrLsig."com.dCntutrfnto( { hnGpadosrco(ucin) Poea. /* * *@aa drcoyTedrcoyfrwihw wn telsig prm ietr h ietr o hc e at h itn *@aa scesalakTeclbc wihwl b cle we drcoylsigi sces prm ucsClbc h alak hc il e ald hn ietr itn s ucsf *@aa fiuealakTeclbc wihwl b cle we drcoylsigecuesa prm alrClbc h alak hc il e ald hn ietr itn notr * / Drcoyitn.<<Action Name>>. ls' /Tl pui.plugin. You need to add the following line to it: <plugin name="Director ListPlugin" value=""com.<<failureCallback>>.0 the addConstructor function above also needed a line to register the native (java) class with PhoneGap's plugin manager.0 the plugin manager was removed and replaced with the res/ ml/plugins. (I am working on a strategy to use Selenium JavaScript to test phonegap) In order to test the plugin.2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android 4.<<Arguments Array>>).. Note that prior to PhoneGap v1. ) .0.lgndrcoyitn.wihato w wn t /el lgn hc cin e at o [ietr].. Finally register both DirectoryListing class as an JavaScript Plugin and register Java Class as the native Plugin (invoked from javascript) /* * * *@eunOjc ltrlsnltnisac o Drcoyitn rtr bet iea igeo ntne f ietrLsig * / vrDrcoyitn =fnto( { a ietrLsig ucin) .

2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android iki.com/ /page/36753494/Ho to Create a PhoneGap Plugin for Android 8/10 .phonegap.

js"></script> <script type="text/javascript" src="directorylisting.innerHTML=innerHtmlText. btn. function printResult(fileInfo){ var innerHtmlText=getHtml(fileInfo).onclick = function() { window.list( "/sdcard".plugins.index++){ htmlText=htmlText+getHtml(fileInfo.addEventListener('deviceready'.2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android Comple e So ce Code <!DOCTYPE HTML> <html> <head> <title>PhoneGap</title> </head> <body> <!-.filename.length. if(fileInfo. iki.phonegap.0. btn. function(e){console.children[index]).log(e) ).children. true). htmlText=htmlText+"</li></ul>".children){ for(var index=0. return htmlText.Place Holder for placing the SD Card Listing --> <div id="result"></div> <hr> <script type="text/javascript" src="phonegap-1.index<fileInfo.Button --> <input disabled id="list-sdcard" type="button" value="List SDCard Contents" /> <hr> <!-.getElementById("list-sdcard"). function getHtml(fileInfo){ var htmlText="<ul><li>"+fileInfo. function() { var btn = document.disabled=false.com/ /page/36753494/Ho to Create a PhoneGap Plugin for Android 9/10 .js"></script> <script type="text/javascript" > document.directoryListing.getElementById("result").0. . document. function(r){printResult(r) .

for now! PDF version iki. Create a ZIP file containing your JAR and JavaScript file. That's it! When people "install" your plugin it will be similar to the process that you used for testing the plugin ..2/27/12 phonegap / Ho to Create a PhoneGap Plugin for Android </script> </body> </html> Packaging he pl gin JAR up your Java source code.phonegap.com/ /page/36753494/Ho to Create a PhoneGap Plugin for Android 10/10 ..

Sign up to vote on this title
UsefulNot useful