4.
You develop your app using the usual three guys
You use the same web view of the native OS
•
•
iOS = UIWebView
Android = android.webkit.WebView
http://phonegap.com/blog/2013/06/20/coming-soon-phonegap30/
Cordova

10.
Cordova plugins
Purpose:
To expose a Phone native functionality to the browser
This is done by developing
•
a custom Native Component
it will be different for each platform
•
a custom JavaScript API
it should be always the same
Mobile Web app
JavaScript
Plugin A
JavaScript
Plugin B
iOS
Plugin A
iOS
Plugin B
Native Platform

11.
Cordova plugin architecture
Since the 3.0 version, Cordova has a slim core with only the very basic native to web bridge
technology
All other APIs are optionally installable
Developers
Cordova contributors
Users
Can compose a version of
PhoneGap suited to their
project needs
Can revision APIs
independently + it is easier to
upgrade and extend APIs
Smaller and faster apps
Plugins are installed and removed using the Cordova CLI instrument

12.
http://phonegap.com/blog/2013/06/20/coming-soon-phonegap30/
Cordova plugin architecture
Comparing it to the old plugin architecture...
Cordova core is now
composed of 17 repos

15.
Recurrent app architecture
App
The app acts as a client for user interaction
Application server
The app communicates with an application server to receive data
Data repository
The application server handles business logic and communicates with a back-end data
repository

16.
The app
It generally uses the single-page application model
•
•
•
•
the application logic is inside a single HTML page
this page is never unloaded from memory
data will be displayed by updating the HTML DOM
data is retrieved from the application server using Ajax

17.
The server
It is a classical web server
•
•
server-side scripting language such as Java, .NET, PHP, etc…
communication can be based on:
- RESTful services (XML, JSON, etc.)
- SOAP
•
it performs business logic, and generally gets or pushes data from a separate repository

18.
The data repository
It may be:
•
•
a standard DB (even deployed in the same machine of the application server)
an external API
Both application server and back-end repository can be provided as a service  BaaS

20.
Cordova CLI
CLI = Command-Line Interface
The main tool to use for the cross-platform workflow
It allows you to:
•
•
•
•
•
•
create new projects
add platforms
build a project w.r.t. different platforms
emulate a project on platform-specific emulators
run a project on device
include specific plugins into a project
If you prefer to use platformspecific SDKs, you can still use it
to initialize your project

23.
Add platforms
With this command you add a target platform of your project.
The platform will appear as subfolder of platforms containing the platform-specific project
mirroring the www folder
You can use an SDK such as Eclipse or
Xcode to open the project you created
•
PLATFORM_NAME
the name of the platform (e.g., ios, android, wp8)
If you do something like this:
cordova platform remove ios
you are removing a specific platform

24.
Build the app
This generates platform-specific code within the project's platforms subdirectory
•
PLATFORM_NAME
the name of the platform to be built (e.g., ios, android, wp8)
If you do not specify the PLATFORM_NAME,
Cordova will build for all installed platforms

25.
emulate/run the app
The emulate command will run the app on a platform-specific emulator
The run command will run the app on a previously setup device (e.g., connected via USB and
configured for being used as device for testing purposes)
•
PLATFORM_NAME
the name of the platform to be built (e.g., ios, android, wp8)

26.
add plugins
The list of plugins can be found here
http://plugins.cordova.io
This generates platform-specific code within the project's platforms subdirectory
•
PLUGIN_ID
the id of the repository containing the source code of the plugin to be added to the project
If the plugin you want to add is not in
the cordova.io registry, you can
directly refer to the URL of his
GitHub repository
If you do something like this:
cordova plugin remove PLUGIN_NAME
you are removing a specific plugin

27.
Platform custom code
Sometimes it may happen to need different JavaScript code, CSS stylesheets or generic assets for
a specific platform
ex.
Android-specific CSS stylesheet
iOS-specific assets for managing the back button graphics
...
In these cases you can put the platform-specific assets into the merges/PLATFORM_NAME folder
Cordova’s build command will take care of integrating them in your deployed app for the specific
platform

32.
Chrome Security Restriction
If you need to test your JSON calls from a local web app, you need to relax Chrome’s security policies
with respect to local files access and cross-domain resources access
•
OSX
open -a Google Chrome.app --args “ --disable-web-security“
•
Windows
chrome.exe --disable-web-security
DO IT ONLY FOR
DEBUGGING!

34.
Ripple
It is based on Ripple, a Chrome
plugin for mobile dev
PRO
•
•
•
very quick
can use Chrome’s Web Development Tools
You can test Cordova’s API from the Desktop
CONS
•
•
browsers’ small differences and bugs
cannot test the interaction with external apps
from Cordova 3.0.0, you need to use
the Ripple available at Apache
npm install -g ripple-emulator
ripple emulate

36.
Simulator
PRO
•
•
Officially supported by platform vendors
CONS
•
device’s performance is not considered
•
You use the “real” device’s browser
•
•
this is iOS-specific
Android’s emulator is a joke
device’s capabilities are only simulated

38.
Remote Debugging
Since Android 4.4, this feature is
available via Chrome’s web dev kit
From iOS 6, Apple provided Mobile Safari with a remote web inspector
 You can debug your app by using the classical web inspector of Desktop Safari
It can connect both to
•
The iOS emulator
•
The real device

43.
My development workflow
1. Code & test using Ripple (very quick)
Quick sketch of layout and complete business logic
2. Run and debug in the XCode simulator (handy & accurate)
Complete the UI for iOS devices and ~99% confidence about business logic
3. Run and debug on devices (complete control & confidence)
Complete the UI for Android too and ~99% confidence about business logic

44.
Remarks
These are MY development environment and development workflow
There are many tools and IDEs out there
 Consider this as a starting point & feel free to use the ones that fit well with your
attitude

46.
Accelerometer
Accelerometer
navigator.accelerometer
It is a global object that captures device motion in the x, y, and z directions
You can call 3 methods on it:
getCurrentAcceleration
watchAcceleration
clearWatch

47.
getCurrentAcceleration
getCurrentAcceleration(win, fail);
It gets the current acceleration along the x, y, and z axis
win
callback function with an Acceleration parameter
fail
error callback

48.
watchAcceleration
var watchID = navigator.accelerometer.watchAcceleration(win, fail, [options]);
It gets the device's current acceleration at a regular interval
win
callback function with an Acceleration parameter, it is called at regular intervals
fail
error callback
options
the interval is specified in the frequency parameter

50.
The Acceleration object
It contains accelerometer data captured at a specific point in time
these values include the effect
of gravity (9.81 m/s^2)
Properties
x (Number): Amount of acceleration on the x-axis. (in m/s^2)
y (Number): Amount of acceleration on the y-axis. (in m/s^2)
z (Number): Amount of acceleration on the z-axis. (in m/s^2)
timestamp (DOMTimestamp): Creation timestamp in milliseconds

54.
Geolocation
The API itself is agnostic of the underlying location information sources
Common sources of location information include
•
Global Positioning System (GPS)
•
location info from IP address, RFID, WiFi,GSM cell IDs, etc.
This API is based on the W3C Geolocation API
Specification, and only executes on devices that
don't already provide an implementation

57.
watchPosition
var id = watchPosition(win, [fail], [options]);
It gets the device's position when a change in position has been detected
win
callback function with an Position parameter
fail
error callback
options
geolocation options

58.
clearWatch
clearWatch(watchID);
Stop watching the position referenced by the watch ID parameter
watchID
ID returned by geolocation.watchPosition

59.
Options
enableHighAccuracy (Boolean)
receive the best possible results (e.g., GPS)
* by default Cordova uses network-based methods
timeout (Number)
the maximum length of time (msec) that is allowed to pass from the call until the
corresponding callback is invoked, otherwise the error callback is called
maximumAge (Number)
accept a cached position whose age is no greater than the specified time in milliseconds

60.
The Position object
Contains the data created by the geolocation API
It is passed as argument to the success callbacks of getCurrentPosition and watchPosition
Properties
•
coords: a set of properties that describe the geographic coordinates of a position
•
timestamp: creation timestamp as a Date object

62.
The Coordinates object
altitude (Number)
height of the position in meters above the ellipsoid
altitudeAccuracy (Number)
accuracy level of the altitude coordinate in meters
http://bit.ly/Ln7V3H

63.
The Coordinates object
heading (Number)
direction of travel, specified in degrees counting clockwise relative to the true north
speed (Number)
current ground speed of the device, specified in meters per second
http://bit.ly/LnanXV

67.
getCurrentHeading
getCurrentHeading(win, [fail], [options]);
It detects the direction or heading that the device is pointed from the top of the device
win
callback function with an Heading parameter
fail
error callback
options
compass options

69.
clearWatch
clearWatch(watchID);
Stop watching the heading of the device by referencing the watchID parameter
watchID
ID returned by heading.watchHeading

70.
Options
frequency (Number)
How often to retrieve the compass heading in milliseconds
filter (Number) iOS only
in iOS the success callback of a watchHeading call can also be called once the sensed
heading values are greater than a given filter
the filter option represents the change in degrees required to initiate a watchHeading
success callback

71.
The CompassHeading object
Properties
magneticHeading (Number)
the heading in degrees from 0-359.99 at a single moment in time
trueHeading (Number)
The heading relative to the geographic North Pole
headingAccuracy (Number)
the deviation in degrees between the reported heading and the true heading
timestamp (Number)
The time at which this heading was determined in milliseconds

75.
Supported formats
They all contain an array of
ConfigurationData objects
The navigator.device.capture object the supported formats it can record in three
properties
supportedAudioModes
The audio recording formats supported by the device
supportedImageModes
The recording image sizes and formats supported by the device
supportedVideoModes
The recording video resolutions and formats supported by the device

76.
The ConfigurationData object
It is used to describe media capture modes supported by the device
Properties
ex.
• video/3gpp
type (String)
• video/quicktime
the string in lower case representing the media type • image/jpeg
• audio/amr
height (Number)
• audio/wav
the height of the image or video in pixels
width (Number)
the height of the image or video in pixels

79.
Options
limit (Number)
not supported in iOS
the maximum number of audio clips the user can record in a single capture operation
duration (Number)
not supported in Android
the maximum duration of an audio sound clip, in seconds

81.
Image capture
captureImage(win, [fail], [options]);
Start the camera application and return information about captured image file(s)
win
callback function with an array of MediaFile parameter
It uses the device's
default camera app
fail
error or when the users cancels the capture operation before capturing any media file
options
compass options
The operation allows the device
user to capture multiple images
in a single session

82.
Options
limit (Number)
not supported in iOS
the maximum number of photos the user can take in a single capture operation

83.
Video capture
captureVideo(win, [fail], [options]);
Start the camera application and return information about captured video file(s)
win
callback function with an array of MediaFile parameter
It uses the device's
default camera app
fail
error or when the users cancels the capture operation before capturing any media file
options
compass options
The operation allows the device
user to capture multiple videos
in a single session

84.
Options
limit (Number)
not supported in iOS
the maximum number of videos the user can take in a single capture operation
duration (Number)
the maximum duration of each video, in seconds

85.
The MediaFile object
A MediaFile encapsulates properties of a media capture file
Properties
name (String): the name of the file, without path information
fullPath (String) : the full path of the file, including the name
type (String): The file's mime type
lastModifiedDate (Date): the date and time that the file was last modified
size (Number): the size of the file, in bytes

86.
MediaFile format data
mediaFile.getFormatData(win, [fail]);
It is used to get information about the format of a captured media file
win
callback function with a MediaFileData parameter
fail
error callback

87.
The MediaFileData object
Encapsulates format information about a media file
Properties
codecs (String): The actual format of the audio and video content
bitrate (Number) : The average bitrate of the content (zero for images)
height (Number): the height of the image or video in pixels (zero for audio clips)
width (Number): the width of the image or video in pixels (zero for audio clips)
duration (Number): the length of the video or sound clip in seconds (zero for images)

89.
Camera
navigator.camera
It provides an home-grown API for capturing images from the device’s default camera
application
It is developed in-house by Cordova in order to provide more options to developers
Methods:
getPicture
cleanup

90.
MediaFile format data
camera.getPicture(win, [fail], [options]);
Takes a photo using the camera or retrieves a photo from the device's album
win
callback function with a image data parameter
fail
error callback
options
capture parameters
The result of getPicture can be:
• a base64 encoded string
• the URI of an image file
Encoding the image using Base64
can cause memory issues on some
devices

91.
getPicture options
getPicture() can be called with the following options

99.
Accelerometer
Media playback
Media
The Media object provides the ability to record and play back audio files on a device
It does not adhere to any W3C
specification, it is just a convenience API
provided by Cordova

105.
Creating contacts
navigator.contacts.create(properties);
One of the few synchronous functions of Cordova
It that returns a new Contact object
The properties parameter is a map of properties of the new Contact object
To persist the Contact object to the device, you have to invoke the Contact.save method

106.
The Contact object
It contains all the properties that a contact can have
Every platform has its own quirks,
you better check them on the
Cordova documentation

107.
The Contact object
A contact object provides the following methods:
clone()
returns a new Contact object that is a deep copy of the calling object, its id property is null
remove(win, fail)
removes the contact from the device contacts database
save(win, fail)
saves a new contact to the device contacts database
updates an existing contact if a contact with the same id already exists

109.
Finding contacts
navigator.contacts.find(fields, win, fail, options);
It queries the device contacts database and returns an array of Contact objects
fields: contact fields to be used as search qualifier. Only these fields will have values in the
resulting Contact objects
win: callback function with the array of contacts returned from the contacts database
fail: error callback
fail: search options to filter contacts

111.
Contact find options
Contains properties that can be used to filter the results
filter (String)
the search string used to find contacts, a case-insensitive, partial value match is applied
to each field specified in the contactFields parameter
multiple (Boolean)
determines if the find operation should return multiple contacts

114.
Accelerometer
Connection
navigator.connection
provides information about the device's cellular and wifi connection
it is synchronous and very fast
You can access a single property
•
connection.type

116.
Accelerometer
Device information
window.device
Contains information about the device’s hardware and software
It is assigned to the window global object

117.
Device properties
A device object provides the following properties:
device.model
http://theiphonewiki.com/wiki/Models
the name of the device's model or product (ex. “iPad 2”, “iPhone 5,1”, etc.)
device.cordova
the version of Cordova running on the device
device.platform
the devices’ operating system (ex. “Android”, “iOS”, etc.)

118.
Device properties
device.uuid
a unique identifier of the user’s device (UUID)
Android: a unique 64-bit integer generated at device’s first boot
iOS: a string of hash values created from multiple hardware identifies
in iOS it is not reliable: The uuid on iOS is not unique to a
device, but varies for each application, for each installation
device.version
the OS version of the device (ex. “4.1”, “2.2”, etc.)

120.
Accelerometer
Events
An event is an action that can be detected by your JavaScript code
In traditional JS programs, any element of the page can have certain events
ontouchstart, onclick, ...
To use any event, you’ll want to use an event listener
document.addEventListener(EVENTNAME, callback, false);

122.
deviceready
It is the most important in event in a Cordova app
Once deviceready is fired, you know two things:
•
The DOM has loaded
•
the Cordova native API are loaded too

123.
App lifecycle events
Based on two main events:
pause
In the pause handler, any calls to the Cordova API or to native
plugins that go through Objective-C do not work,, they are
only processed when the app resumes.
fires when an application is put into the background
resume
fires when a paused application is put back into the foreground
resign, active
iOS-specific events that are triggered when the users locks/unlocks the device

124.
Connection events
Based on two main events:
online
fires when the application's network connection changes to being online
(that is, it is connected to the Internet)
offline
fires when the application's network connection changes to being offline
(that is, no Internet connection available)

125.
Battery events
Based on two main events:
This value is device-specific
batterycritical
fires when the battery has reached the critical level threshold
batterylow
similar to batterycritical, but with a higher threeshold
batterystatus
fires a change in the battery status is detected
The battery status must
change of at least 1%

126.
Battery events
The handler of a battery event is always called with an object that contains two properties:
level (Integer)
The percentage of battery (0-100)
isPlugged (Boolean)
true if the device is plugged to the battery charger

128.
Alert
navigator.notification.alert(message, callback, [title], [button]);
Shows a custom alert to the user
•
message: the string to present to the user
•
callback: the function invoked when the user taps on the button
•
title: title of the alert (default is “Alert”)
•
button: name of the confirm button (default is “Ok”)

129.
Confirm
navigator.notification.alert(message, callback, [title], [buttons]);
Similarly to alert, it shows a customizable confirmation dialog to the user
•
message: the string to present to the user
•
callback: the function invoked when the dialog is dismissed
it takes a “buttonIndex“ parameter to know which button has been pressed (it starts from 1)
•
title: title of the dialog (default is “Confirm”)
•
buttons: comma-separated string containing the button labels (default is “Ok, Cancel”)

130.
Prompt
navigator.notification.prompt(message, callback, [title], [buttons], [text]);
It shows a customizable dialog with a prompt to the user
•
message: the string to present to the user
•
callback: the function invoked when the dialog is dismissed
it takes a “results“ parameter to know which button has been pressed (it starts from 1) and
the text entered by the user
•
title: title of the dialog (default is “Prompt”)
•
buttons: comma-separated string containing the button labels (default is “Ok, Cancel”)
•
text: default text in the input box

131.
Beep
navigator.notification.beep(times);
It playes a beep sound
•
times (Number): the number of times to repeat the beep
Android plays the default "Notification ringtone" specified
under the "Settings/Sound & Display" panel

132.
Vibration
navigator.notification.vibration(milliseconds);
It vibrates the device
•
milliseconds (Number): the duration of the vibration
iOS ignores the milliseconds parameter, it always vibrates for a
fixed amount of time

136.
WebSQL
It provides you a structured SQL relational database
You have to setup a DB schema
You can then perform classical SQL queries
tx.executeSql("SELECT * FROM User“, [],
function(tx, result) {
// callback code
});

137.
IndexedDB
•
It tries to combine Web Storage and WebSQL
•
You can save data as key/value pairs
•
You can define multiple DBs
•
Good Performance
data is indexed
asynchronous
You can see a store as a big SQL table with only key/value pairs
 you don’t need to define a schema upfront
it does not block the UI

139.
Considerations
You will likely use more than one API in combination
 Use the right API for the right job
Web Storage
•
it is not transactional  race conditions
•
very simple API, no schema
•
only String data  performance issues for complex data due to JSON serialization
•
session storage will be cleared after the app is closed
•
limited quota

142.
Considerations
File System
asynchronous  does not block the UI
not transactional
indexing and search are not built-in  you have to implement your lookup functions
unlimited quota  useful for images, videos, documents, etc.