DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

  1. DZone
  2. Refcards
  3. Getting Started With PhoneGap
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.

Download Refcard
Free PDF for Easy Reference
refcard cover

Written By

author avatar Raymond Camden
Senior Developer Evangelist, Adobe
Table of Contents
► About Adobe PhoneGap ► Getting Started ► Other APIs ► Testing PhoneGap Apps ► PhoneGap Support
Section 1

About Adobe PhoneGap

by: Raymond Camden

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

​x
1
​
2
cordova create somedir org.sample.test test
3
​

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:

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:

4
1
​
2
cordova platform add ios
3
cordova platform add android
4
​

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

3
1
​
2
cordova build
3
​

And then passing it to the emulator:

3
1
​
2
cordova emulate
3
​

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

iphone-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:

3
1
​
2
<script type="text/javascript" src="cordova.js"></script>
3
​

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:

7
1
​
2
document.addEventListener('deviceready', deviceready, false);
3
​
4
function deviceready() {
5
        console.log('deviceready');
6
}
7
​

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.

20
1
​
2
<!DOCTYPE html>
3
<html>
4
    <head>
5
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
6
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width;" />
7
        <link rel="stylesheet" type="text/css" href="css/index.css" />
8
        <title>Camera Example</title>
9
    </head>
10
    <body>
11
​
12
        <button id="getPicture">Take Picture</button>
13
​
14
        <img id="pictureResult">
15
​
16
        <script type="text/javascript" src="cordova.js"></script>
17
        <script type="text/javascript" src="js/index.js"></script>
18
    </body>
19
</html>
20
​

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

10
1
​
2
button {
3
    width: 80%;
4
    height: 30px;
5
    font-size: 1.1em;
6
    margin-left: auto;
7
    margin-right: auto;
8
    display: block;
9
}
10
​

Here is how it looks in the iOS Simulator:

take-picture

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

29
1
​
2
document.addEventListener("deviceready", ready, false);
3
​
4
function ready() {
5
        var camBtn = document.querySelector("#getPicture");
6
        camBtn.addEventListener("touchstart", beginCamera, false);
7
}
8
​
9
function beginCamera(e) {
10
        e.preventDefault();
11
​
12
        navigator.camera.getPicture(cameraSuccess, cameraError, 
13
                { 
14
                        quality:50,
15
                        destinationType: Camera.DestinationType.FILE_URI,
16
                        targetWidth:350,
17
                        targetHeight:350
18
                });
19
​
20
}
21
​
22
function cameraError(e) {
23
        navigator.notification.alert("Sorry, the camera didn't work.", null);
24
}
25
​
26
function cameraSuccess(uri) {
27
        document.querySelector("#pictureResult").src = uri;
28
}
29
​

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.

alert

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.

boba

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:

16
1
​
2
document.addEventListener("deviceready", init, false);
3
​
4
function init() {
5
​
6
        document.addEventListener("online", toggleCon, false);
7
        document.addEventListener("offline", toggleCon, false);
8
​
9
        if(navigator.network.connection.type == Connection.NONE) {
10
                navigator.notification.alert("Sorry, you are offline.", function() {}, "Offline!");
11
        } else {
12
                someFunc();
13
        }
14
​
15
}
16
​

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.

12
1
​
2
document.addEventListener("deviceready", init, false);
3
​
4
function init() {
5
        var deviceDesc = "";
6
                 deviceDesc += "Device Name: " + device.name + "<br/>";
7
                 deviceDesc += "Device Platform: " + device.platform + "<br/>";
8
                 deviceDesc += "Device Version: " + device.version + "<br/>";
9
​
10
                 document.querySelector("#device").innerHTML = deviceDesc
11
}
12
​

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.

Accelerometer

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.

Capture

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.

Compass

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.

Contacts

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).

Events

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.

Geolocation

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.

Globalization

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.

Notification

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'.

Like This Refcard? Read More From DZone

related article thumbnail

DZone Article

Internationalization Using jquery.i18n.properties.js
related article thumbnail

DZone Article

How to Convert XLS to XLSX in Java
related article thumbnail

DZone Article

Automatic Code Transformation With OpenRewrite
related article thumbnail

DZone Article

Accelerating AI Inference With TensorRT
related refcard thumbnail

Free DZone Refcard

Swift Essentials
related refcard thumbnail

Free DZone Refcard

Mobile Web Application Testing
related refcard thumbnail

Free DZone Refcard

Getting Started With PhoneGap
related refcard thumbnail

Free DZone Refcard

HTML5 Mobile Development

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: