refcard cover
Refcard #191

Getting Started With PhoneGap

The Framework for Hybrid Mobile Apps

Provides an introduction to PhoneGap, and is intended for experienced developers who have a basic conceptual grasp of mobile app development.

Free PDF for Easy Reference
refcard cover

Written By

author avatar Raymond Camden
Senior Developer Evangelist, Adobe
Section 1

About Adobe PhoneGap

Adobe PhoneGap is an open source framework that lets you build hybrid mobile applications using HTML, JavaScript, and CSS. In 2012, the PhoneGap source became a top-level project under the Apache Software Foundation with the name "Cordova." (You may hear people refer to PhoneGap and Cordova interchangeably.)

PhoneGap provides support for using web standards to creative native applications that run on seven different mobile platforms:

  • Android
  • iOS
  • Windows Phone
  • Blackberry
  • WebOS
  • Symbian
  • Bada

This Refcard is intended for experienced developers who have a basic conceptual grasp of mobile app development. The card does not presuppose any real-world mobile dev experience, but experienced mobile developers will probably find the card especially useful.

Along with creating installable mobile web applications, PhoneGap provides a JavaScript bridge to your devices native hardware. This provides support within your JavaScript for the following features:

Feature Description
Accelerometer Allows for tracking the devices movement, noticing ‘shakes’ and orientation.
Camera Allows the user to take a picture for your application or access pictures on the device.
Capture Allows for video and audio capture.
Compass Returns compass directions for the device.
Connection Lets your application determine if there is a connection as well as how strong it is.
Device Returns basic metadata about the device.
Events Support for various device related events, including battery level changes.
File File system access for the device. Includes basic read/write functionality for both files and directories.
Geolocation Allows you to locate the user.
Globalization Support for formatting numbers and dates in the user’s native language.
InAppBrowser A way to provide web access to URLs without the user leaving your application.
Media Audio recording and playback support.
Notification Various ways to get the user’s attention, including sound and vibration-based alerts.
Splashscreen Let’s your application customize the startup experience.
Storage Provides a single-user database for your application.
Section 2

Getting Started

Each of the platforms supported by PhoneGap has its own Getting Started guide. Since these guides are very platform specific, readers are encouraged to visit the main documentation listing (http://docs.phonegap.com/en/2.5.0/guide_getting-started_index.md.html#Getting%20Started%20Guides) and select the guide for their platform.

In general, the process involves getting the SDK for your platform and then downloading the PhoneGap SDK. In some cases, like Android, other tools are required, like Apache Ant. In other cases, you need to purchase a developer program membership before you can use PhoneGap with that platform (iOS is an example of that).

Once you've finished the installation procedure for your frameworks of choice, projects can be created at the command line. For this reference guide we will make use of the Cordova command line program. While not part of the PhoneGap SDK, it is fully compatible with PhoneGap projects and can be used with the downloaded SDK. Here is an example

cordova create somedir org.sample.test test

In the example above, a new project will be created in a subdirectory called somedir, using the ID of org.sample.test, and using an application named test. Both the ID and application name values are optional. The directory will contain the following folders:


For now, just concern yourself with the platforms and www folder. The platforms folder will contain a platform-specific install of whatever device types you want to support. So for example, if you wanted to build an app for iOS and Android, there would be two folders underneath it. Since you just created the project this will be empty at first. The www folder is the actual HTML, JavaScript, CSS, and related assets for your application. This is where you will edit your code. The cordova command line will handle copying your files into the appropriate platform directories. To go ahead and add support for iOS and Android, you would type:

cordova platform add ios
cordova platform add android

By default, the www folder already contains some basic assets, so you can immediately test out your project by first building it:

cordova build

And then passing it to the emulator:

cordova emulate

Here's the default application running in the iOS emulator:


Using PhoneGap's Features

Now that you know how to create a project, build it, and deploy it to a simulator, how do you actually make use of PhoneGap's features?

Each PhoneGap project ships with a JavaScript file, cordova.js, that provides hooks to native device features not normally available to web pages on the device. The file, cordova.js, will not be present in the www folder you just created. Yet you can see it included by the default index.html file:

<script type="text/javascript" src="cordova.js"></script>

How does this work? When you create a build, the command line tool will copy your HTML, JS, and other assets into the platform folder and automatically include the proper cordova.js file for each unique platform.

The next step is crucial. When your application starts up, it will not be ready to use any special devices features. Instead, it must wait for the application to initialize those hooks and listen for an event called deviceready. Here's a simple example of that in action:

document.addEventListener('deviceready', deviceready, false);

function deviceready() {

Once the deviceready event is fired, you can then use any of the PhoneGap features your application requires.

Using the Camera

As an example of using the PhoneGap API, let's build a simple application that makes use of the device camera. First, let's begin with some simple HTML.

<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width;" />
        <link rel="stylesheet" type="text/css" href="css/index.css" />
        <title>Camera Example</title>

        <button id="getPicture">Take Picture</button>

        <img id="pictureResult">

        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>

In order to make the button a bit easier to use, we've added a simple CSS file to make it fatter:

button {
    width: 80%;
    height: 30px;
    font-size: 1.1em;
    margin-left: auto;
    margin-right: auto;
    display: block;

Here is how it looks in the iOS Simulator:


Now that we've got the layout built, let's look at the code.

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

function ready() {
        var camBtn = document.querySelector("#getPicture");
        camBtn.addEventListener("touchstart", beginCamera, false);

function beginCamera(e) {

        navigator.camera.getPicture(cameraSuccess, cameraError, 
                        destinationType: Camera.DestinationType.FILE_URI,


function cameraError(e) {
        navigator.notification.alert("Sorry, the camera didn't work.", null);

function cameraSuccess(uri) {
        document.querySelector("#pictureResult").src = uri;

The file begins with a simple event handler for the deviceready event. PhoneGap will fire this automatically when it is safe to use device APIs.

In the beginCamera function you can see the call to navigator.camera.getPicture. The first two arguments are a success and error handler respectively. The third argument is a set of options that let you customize how the camera will be used. In our example, we've specified a quality of 50, a destination type of a file uri, and a target width and height of 350 pixels.

The cameraError function makes use of another part of the PhoneGap API, the notification feature. If the user's device doesn't have a camera (or something else goes wrong), this notification will be displayed.


The cameraSuccess handler is fired after a picture is selected. Since we elected to have a FILE_URI sent, we can simply use that in our DOM. We select the image and assign the URI to the src attribute.


Camera API Overview

Method Description
navigator.camera.getPicture(success handler, error handler, options) Main method for getting picture data. It also supports getting a picture from the user’s existing collection of photos. Other options include desired quality and size as well as encoding type.
navigator.camera.cleanup A utility to remove photos that may exist in the application’s temporary directory.

Using the Connection API

Another useful feature of the PhoneGap API is the Connection API. PhoneGap apps run locally on a device. Technically, they do not need to be online to perform their tasks. In this code snippet, we inspect the connection device connection status as well as listen for changes:

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

function init() {

        document.addEventListener("online", toggleCon, false);
        document.addEventListener("offline", toggleCon, false);

        if(navigator.network.connection.type == Connection.NONE) {
                navigator.notification.alert("Sorry, you are offline.", function() {}, "Offline!");
        } else {


By using a little bit of code your application can then intelligently respond to changes in the device's connection to the Internet. You can even check the strength of the connection. This would be useful for deciding if it makes sense to stream large files.

Connection Object Values

The following is a list of each constant available in the navigator.network.connection object:

  • Connection.UNKNOWN
  • Connection.ETHERNET
  • Connection.WIFI
  • Connection.CELL_2G
  • Connection.CELL_3G
  • Connection.CELL_4G
  • Connection.CELL
  • Connection.NONE

Using the Device API

Another useful feature is the Device API. While not exactly an API, the device object returns values for the name, platform, version, model, as well as the currently running version of PhoneGap. If your code needs to do something slightly different for iOS versus Android, this is what you would use.

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

function init() {
        var deviceDesc = "";
                 deviceDesc += "Device Name: " + device.name + "<br/>";
                 deviceDesc += "Device Platform: " + device.platform + "<br/>";
                 deviceDesc += "Device Version: " + device.version + "<br/>";

                 document.querySelector("#device").innerHTML = deviceDesc

Device Object Values

The following is a list of each constant available in the device object:

  • device.name
  • device.cordova
  • device.platform
  • device.uuid
  • device.version
  • device.model
Section 3

Other APIs

Now let's take a quick tour through the rest of PhoneGap's APIs. This is not a complete list but covers the most important (and useful) features.


Method Description
navigator.accelerometer. getCurrentAcceleration(success handler, error handler) Returns the “acceleration”, or current movement, of the device in X, Y, Z values.
navigator.accelerometer. watchAcceleration(success handler, error handler, options) Will repeatedly check the device’s acceleration. This can be stopped with navigator.accelerometer.clearWatch.


Method Description
navigator.capture. captureAudio(success handler, error handler, options) Allows the user to record one or more audio clips. Could be used to let the user verbally annotate data.
navigator.capture. captureImage(success handler, error handler, options) For the most part very similar to the Camera API, but allows for multiple captures.
navigator.capture. captureVideo(success handler, error handler, options) Allows the user to record one or more video clips. You can use the options to specify a max duration.


Method Description
navigator.compass. getCurrentHeading (success handler, error handler) Returns the compass heading of the device as a value from 0 to 359.99.
navigator.compass. watchHeading(success handler, error handler, options) Will repeatedly check the device’s compass direction. This can be stopped with navigator.compass.clearWatch.


Method Description
navigator.contacts.create (properties) Allows for the creation of a new contact.
navigator.contacts.find(fields, success handler, error handler, options) Performs a search against the device contact database. You can search against multiple fields (like name or email).


Type Description
deviceready The most important event. Nothing should be used until after this event is fired!
pause/resume Fired when an application pauses or is resumed.
online/offline Fired when the device gains or loses network connectivity.
backbutton For devices that have a back button, this event can be used to detect its use.
batterycritical/batterylow/batterystatus Various battery level events are available. Would be useful to remind the user to save data when the battery is low.
menubutton For deices that have a menu button, this event can be used to detect its use.
searchbutton For deices that have a search button, this event can be used to detect its use.
startcallbutton/endcallbutton A Blackberry-only set of events related to calls.
volumedownbutton/volumeupbutton A Blackberry-only set of events related to the device volume.


Method Description
navigator.geolocation.getCurrentPosition (success handler, error handler, options) Returns the position of the device.
navigator.geolocation.watchPosition(success handler, error handler, options) Will repeatedly check the device’s location. This can be stopped with navigator.geolocation.clearWatch.


Method Description
navigator.globalization.getPreferredLanguage (success handler, error handler) Returns the device's default language setting. There is also a globalization.getLocaleName method.
navigator.globalization.dateToString(date, success handler, error handler, options) Converts a date into a format recognizeable by the device's locale. The reverse method is stringToDate.
navigator.globalization.getDatePattern(success handler, error handler, options) / getNumberPattern / getCurrentPattern. Returns a "pattern" representing the date format for the device's locale. Also supports numbers and currency via their own methods.
navigator.globalization.getDateNames(success handler, error handler, options) Returns either an array of month names or week days based on the device's locale.
navigator.globalization.isDayLightSavingsTime(date, success handler, error handler) Determines if daylight savings is in effect for a particular date.
navigator.globalization.getFirstDayOfWeek(success handler, error handler) Returns a number between 1 and 7 (where 1 is Sunday) representing the device's locale's initial week day.
navigator.globalization.numberToString(date, success handler, error handler, options) Converts a number into a format recognizeable by the device's locale. The reverse method is stringToNumber. The method supports decimals, percents, and currency values.


Method Description
navigator.notification.alert(message, callback, title, button) Creates a visual notification of a simple message.
navigator.notification.confirm(message, callback, title, buttons) Creates a visual notification that asks for confirmation.
navigator.notification.prompt(message, callback, title, button) Creates a visual notification that asks the user to enter some data.
navigator.notification.beep(times) Creates an audio alert.
navigator.notification.vibrate(milliseconds) Vibrates the device.
Section 4

Testing PhoneGap Apps

While you can use the command line to build and test PhoneGap apps, there are a few other options you may wish to consider.

Feature Description
The Ripple Emulator Ripple is a Chrome extension that lets you test PhoneGap apps in the browser. While not a 100% complete mirror of the PhoneGap functionality, it allows for testing of almost all of the PhoneGap feature set. This extension is free and may be downloaded here: http://bit.ly/10VCTsK
PhoneGap Build PhoneGap Build (build.phonegap.com) is a free online service. By connection to your GitHub account, or uploading a simple zip file, you can make use of their own compilation services. This allows people to create builds for multiple platforms at once, all in the cloud!
Section 5

PhoneGap Support

PhoneGap offers commercial support subscriptions (http://phonegap.com/support) that lead developers from app design and development through testing and deployment. Subscriptions include access to live online training and knowledge base, weekly chat office hours & a private forum staffed by a professional technical support team.

For community support, PhoneGap Google Group (https://groups.google.com/forum/?fromgroups#!forum/phonegap) is quite active. Topics range from focused, Stack Overflow-style problem-solving to rich discussions on broader questions like 'how do you develop for X resolution'.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}