SlideShare una empresa de Scribd logo
1 de 115
Descargar para leer sin conexión
Gran Sasso Science Institute
Ivano Malavolta
Apache Cordova
Roadmap
•  The Cordova framework
•  Recurrent app architecture
•  Cordova CLI
•  Debugging Cordova applications
•  My development environment
•  Cordova APIs
PhoneGap VS Cordova
Adobe/Nitobi donated the PhoneGap codebase to the Apache foundation
à 
wider audience and contributors
à 
transparent governance


Better documentation
à 
easier contributions for companies


Apache Licensing
There was only one problem....


trademark ambiguity 

à CORDOVA
PhoneGap is a distribution of
Apache Cordova
Cordova
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
The UI layer is a web browser view
•  100% width
•  100% height

Headless web browser
•  No URL bar
•  No decorations
•  No zooming
•  No text selection
Can I use HTML5, JS and CSS libraries I use
everyday?
How does Cordova work?
Features 
coverage
When Cordova API is not enough...
Sometimes Cordova is not enough as is for our purposes
•  unsupported feature
•  heavyweight data processing is faster in native code



ex. images manipulation
•  background processing is better handled natively



ex. files sync
•  complex business logic

à You can develop a
Cordova plugin
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
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 




Plugins are installed and removed using the Cordova CLI instrument
Developers

Can compose a version of
Cordova suited to their
project needs
Cordova contributors

Can revision APIs
independently + it is easier
to upgrade and extend APIs
Users

Smaller and faster apps
Cordova plugin architecture
Cordova core is now
composed of 17 repos
Comparing it to the old plugin architecture...
http://phonegap.com/blog/2013/06/20/coming-soon-phonegap30/
Examples of available plugins
Please, notice the
upload dates J
Roadmap
•  The Cordova framework
•  Recurrent app architecture
•  Cordova CLI
•  Debugging Cordova applications
•  My development environment
•  Cordova APIs
Recurrent app architecture


The app acts as a client for user interaction

The app communicates with an application server to receive data

The application server handles business logic and communicates with a back-end data
repository
App
Application server
Data repository
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
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 
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
Roadmap
•  The Cordova framework
•  Recurrent app architecture
•  Cordova CLI
•  Debugging Cordova applications
•  My development environment
•  Cordova APIs
Cordova CLI


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
CLI = Command-Line Interface
If you prefer to use platform-
specific SDKs, you can still use it
to initialize your project
Creates template project
•  PATH 

the folder that will contain your project
•  ID 
 

package identifier in reverse-domain style (optional)
•  NAME 

display name of the app (optional)
Project creation
The create command creates a 
predefined project structure
•  merges

a mirror of the www folder containing platform-specific assets
•  platforms 
platform specific projects (ex. an Eclipse project for Android, XCode for iOS)
•  plugins 

installed plugins (both JS files and native resources)
•  www 

contains your HTML, JS, CSS files 
Project structure
config.xml contains core Cordova API
features, plugins, and platform-specific
settings. See here for the iOS values: 


 
 
 
 
http://goo.gl/1CcmyL
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	
  
•  PLATFORM_NAME



the name of the platform (e.g., ios, android, wp8)
Add platforms
If you do something like this:

cordova	
  platform	
  remove	
  ios	
  

you are removing a specific platform
You can use an SDK such as Eclipse or
Xcode to open the project you created
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)
Build the app
If you do not specify the
PLATFORM_NAME, Cordova will build for
all installed platforms
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)
emulate/run the app
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
add plugins
If you do something like this:

cordova	
  plugin	
  remove	
  PLUGIN_NAME	
  

you are removing a specific plugin
The list of plugins can be found
here
http://plugins.cordova.io
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
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
Platform custom code
Roadmap
•  The Cordova framework
•  Recurrent app architecture
•  Cordova CLI
•  Debugging Cordova applications
•  My development environment
•  Cordova APIs
The killer app!
•  Check console
•  Breakpoints
•  Update the DOM at run-time
•  Access to all local DBs
•  Network profiling
•  CPU and memory profiling
•  Monitor event listeners
•  Monitor elements’ rendering time
Desktop Browser
•  very quick
•  very handy functions
•  see Chrome’s Web Development Tools
•  Breakpoints


PRO
•  browsers’ small differences and bugs
•  cannot test all Cordova’s specific functionalities
•  you need Phonegap shims 

CONS
Desktop Browser
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!
Desktop Browser - Tools
Browser’s extension for window dimensions

Resolution Test

http://goo.gl/fQpbH


PhoneGap Shims, there are many, this is the most used:

PhoneGap-Desktop

https://github.com/jxp/phonegap-desktop
Ripple
•  very quick
•  can use Chrome’s Web Development Tools
•  You can test Cordova’s API from the Desktop
•  browsers’ small differences and bugs
•  cannot test the interaction with external apps
PRO
CONS
It is based on Ripple, a Chrome
plugin for mobile dev 



from Cordova 3.0.0, you need to use
the Ripple available at Apache 
npm	
  install	
  -­‐g	
  ripple-­‐emulator	
  
ripple	
  emulate	
  
Apache Ripple
Simulator
•  Officially supported by platform vendors 

•  You use the “real” device’s browser
PRO
•  device’s performance is not considered 
•  this is iOS-specific
•  Android’s emulator is a joke
•  device’s capabilities are only simulated
CONS
On device
•  accurate
•  still handy
•  real performance tests
•  real browser tests
PRO
•  Deployment takes some time (~6 seconds for iOS)
CONS
Remote Debugging
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

Since Android 4.4, this feature is
available via Chrome’s web dev kit
Remote Debugging for older platforms

Weinre http://people.apache.org/~pmuellr/weinre/docs/latest/

3 main components: 
Debug Server
the HTTP server for debug data
Debug Target
the (web) app you are debugging
Debug Client
the Web Inspector user interface
Public debug server: 
debug.phonegap.com
Debugging reference table 
Make a favor to yourself, 
don’t debug craftsman way:

console.log()	
  +	
  alert()	
  

iOS
 Android
Desktop Browser
 
 
Ripple
 
 
Device/emulator
 
 
Weinre
 
 
Safari Web
Inspector

 X
Chrome Web
Inspector
X
Roadmap
•  The Cordova framework
•  Recurrent app architecture
•  Cordova CLI
•  Debugging Cordova applications
•  My development environment and workflow
•  Cordova APIs
My development environment
Sublime Text 2
http://www.sublimetext.com
SublimeText Package Control
http://wbond.net/sublime_packages/package_control
Sidebar Enhancer
https://github.com/titoBouzout/SideBarEnhancements
HTML Prettify
https://github.com/victorporof/Sublime-HTMLPrettify
SublimeLinter
https://github.com/SublimeLinter/SublimeLinter
JsFormat
https://github.com/jdc0589/JsFormat
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
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
Roadmap
•  The Cordova framework
•  Recurrent app architecture
•  Cordova CLI
•  Debugging Cordova applications
•  My development environment
•  Cordova APIs

•  Accelerometer
•  Compass
•  Capturing audio and video & camera
•  Media playback
•  Contacts
•  Connection 
•  Device information
•  Events
•  Notification
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	
  
Accelerometer
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	
  
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 	
  
clearWatch
clearWatch(watchID);	
  
Stop watching the Acceleration referenced by the watch ID parameter

watchID

 ID returned by accelerometer.watchAcceleration
The Acceleration object

It contains accelerometer data captured at a specific point in time

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
these values include the effect 
of gravity (9.81 m/s^2)
Accelerometer example
var	
  options	
  =	
  {	
  frequency:	
  3000	
  };	
  
var	
  watchID	
  =	
  navigator.accelerometer.watchAcceleration(win,	
  fail,	
  options);	
  
	
  
function	
  win(acc)	
  {	
  
	
  if((acc.x	
  ==	
  0)	
  &&	
  (acc.y	
  ==	
  0)	
  &&	
  (acc.z	
  ==	
  9,81)) 	
  	
  {	
  
	
   	
  console.log(“I	
  am	
  on	
  a	
  table”);	
  
	
   	
  stop();	
  
	
  }	
  else	
  {	
  
	
   	
  console.log(“Please,	
  leave	
  me	
  on	
  the	
  table”);	
  
	
  }	
  
}	
  
function	
  fail()	
  {	
  
	
  console.log(“error”);	
  
}	
  
	
  
function	
  stop()	
  {	
  
	
  if(watchID)	
  {	
  
	
   	
  navigator.accelerometer.clearWatch(watchID);	
  
	
   	
  watchID	
  =	
  null;	
  
	
  }	
  
}	
  
	
  
Shake detection
var	
  previousReading	
  =	
  {x:	
  null,	
  y:	
  null,	
  z:	
  null};	
  
	
  
navigator.accelerometer.watchAcceleration(function	
  (reading)	
  {	
  
	
  var	
  changes	
  =	
  {},	
  
	
  threshold	
  =	
  30;	
  
	
  if	
  (previousReading.x	
  !==	
  null)	
  {	
  
	
   	
  changes.x	
  =	
  Math.abs(previousReading.x,	
  reading.x);	
  
	
   	
  changes.y	
  =	
  Math.abs(previousReading.y,	
  reading.y);	
  
	
   	
  changes.z	
  =	
  Math.abs(previousReading.z,	
  reading.z);	
  
	
  }	
  
	
  if	
  (changes.x	
  +	
  changes.y	
  +	
  changes.z	
  >	
  (threshold	
  *	
  3))	
  {	
  
	
   	
  console.log(“shake	
  detected”);	
  
	
  }	
  
	
  previousReading	
  =	
  {	
  
	
   	
  x:	
  reading.x,	
  
	
   	
  y:	
  reading.y,	
  
	
   	
  z:	
  reading.z	
  
	
  }	
  
},	
  errorCallback,	
  {	
  frequency:	
  300	
  });	
  
Accelerometer
navigator.device.capture	
  

Provides access for capturing directly from the device	
  
Audio
Image
Video

Capturing Audio and Video
Omogeneous APIs between audio, image, and video
capturing based on a W3C specification
Supported formats

The navigator.device.capture	
  object contains 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
They all contain an array of 
ConfigurationData objects
The ConfigurationData object

It is used to describe media capture modes supported by the device
Properties
 type (String)
the string in lower case representing the media type
height (Number)
the height of the image or video in pixels
width (Number)
the height of the image or video in pixels
ex.
•  video/3gpp
•  video/quicktime
•  image/jpeg
•  audio/amr
•  audio/wav
Supported format example
var	
  imageModes	
  =	
  navigator.device.capture.supportedImageModes;	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  for(var	
  i=0;	
  i	
  <imageModes.length;	
  i++)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  var	
  mode	
  =	
  imageModes[i];	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  console.log(mode.type);	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  console.log(mode.height);	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  console.log(mode.width);	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  }	
  
Audio capture
captureAudio(win,	
  [fail],	
  [options]);	
  
Starts the audio recorder app and returns information about captured audio clip files
win

callback function with an array of MediaFile parameter
fail

error or when the users cancels the capture operation before capturing any media file
options
audio capture options
It uses the device's default
audio recording app
The operation allows the device
user to capture multiple
recordings in a single session
Options

limit (Number)

the maximum number of audio clips the user can record in a single capture operation
duration (Number)

the maximum duration of an audio sound clip, in seconds
not supported in iOS
not supported in Android
Audio capture example
var	
  options	
  =	
  {	
  limit:	
  2,	
  duration:	
  5	
  };	
  
	
  
navigator.device.capture.captureAudio(win,	
  fail,	
  options);	
  
	
  
function	
  win(mediaFiles)	
  {	
  
	
  var	
  i;	
  
	
  for	
  (i=0;	
  i<mediaFiles.length;	
  i++)	
  {	
  
	
   	
  console.log(mediaFiles[i]);	
  
	
  }	
  	
  	
  	
  	
  	
  	
  
}	
  
	
  
function	
  fail(error)	
  {	
  
	
  console.log(‘Error	
  with	
  code:	
  '	
  +	
  error.code);	
  
}	
  
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
fail

error or when the users cancels the capture operation before capturing any media file
options
image capture options
It uses the device's
default camera app
The operation allows the device
user to capture multiple images
in a single session
Options

limit (Number)

the maximum number of photos the user can take in a single capture operation

not supported in iOS
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
fail

error or when the users cancels the capture operation before capturing any media file
options
video capture options
It uses the device's
default camera app
The operation allows the device
user to capture multiple videos
in a single session
Options

limit (Number)

the maximum number of videos the user can take in a single capture operation
duration (Number)

the maximum duration of each video, in seconds

not supported in iOS
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
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
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)
Capture Error
Encapsulates the error code resulting from a failed media capture operation

It contains a pre-defined error code
CaptureError.CAPTURE_INTERNAL_ERR
CaptureError.CAPTURE_APPLICATION_BUSY
CaptureError.CAPTURE_INVALID_ARGUMENT
CaptureError.CAPTURE_NO_MEDIA_FILES
CaptureError.CAPTURE_NOT__SUPPORTED
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
Getting pictures from the camera
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
getPicture options

getPicture() can be called with the following options
getPicture options
quality (Number)

quality of saved image 
Range [0, 100]
allowEdit (boolean)

allow simple editing of the image before selection
destinationType (Number)
getPicture options
sourceType (Number)



encodingType (Number)
getPicture options
mediaType (Number)




correctOrientation (boolean)
Rotate the image to correct for the orientation of the device during capture
getPicture options
saveToPhotoAlbum (boolean)
Save the image to the photo album on the device after capture

popoverOptions (object)
iPad only
getPicture options
targetWidth, targetHeight (Number)

width/height in pixels to scale image

cameraDirection (Number)
Camera cleanup
camera.cleanup(win,	
  [fail]);	
  
Removes intermediate photos taken by the camera from temporary storage
win

callback function
fail

error callback

 Valid only when 
•  the value of Camera.sourceType === Camera.PictureSourceType.CAMERA
•  the Camera.destinationType === Camera.DestinationType.FILE_URI
iOS only
Camera example
var	
  options	
  =	
  {	
  quality:	
  50,	
  
	
  destinationType:	
  destinationType.FILE_URI,	
  
	
  sourceType:	
  pictureSource.PHOTOLIBRARY	
  	
  
});	
  
	
  
navigator.camera.getPicture(win,	
  fail,	
  options);	
  
	
  
function	
  win(imageURI)	
  {	
  
	
  var	
  element	
  =	
  $(“#block”);	
  
	
  element.src(imageURI);	
  
}	
  
	
  
function	
  fail	
  (error)	
  {	
  
	
  console.log(error);	
  //	
  this	
  is	
  provided	
  by	
  the	
  device’s	
  native	
  code	
  
}	
  
Accelerometer
Media	
  

The Media object provides the ability to record and play back audio files on a device


Media playback
It does not adhere to any W3C
specification, it is just a convenience API
provided by Cordova
The Media object
var	
  media	
  =	
  new	
  Media(src,	
  win,	
  [fail],	
  [status]);	
  
src (String): A URI containing the audio content

The URI can be local or can be a URL addressable by a standard HTTP get request
win: callback executed when the object executes a play, record, or stop action
fail: error callback
status: callback executed to indicate status changes

Media status possible parameters:

•  Media.MEDIA_NONE = 0;
•  Media.MEDIA_STARTING = 1;
•  Media.MEDIA_RUNNING = 2;
•  Media.MEDIA_PAUSED = 3;
•  Media.MEDIA_STOPPED = 4;
Media methods
Media Error
Encapsulates the error code resulting from a failed media operation

It contains a pre-defined error code
MediaError.MEDIA_ERR_ABORTED
MediaError.MEDIA_ERR_NETWORK
MediaError.MEDIA_ERR_DECODE
MediaError.MEDIA_ERR_NONE_SUPPORTED
Media example
var	
  media	
  =	
  new	
  Media(“http://path/to/mp3”,	
  win,	
  fail);	
  
	
  
//	
  every	
  second	
  we	
  log	
  the	
  position	
  
var	
  myTimer	
  =	
  setInterval(function	
  ()	
  {	
  
	
  media.getCurrentPosition(	
  
	
   	
  function	
  (position)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  if	
  (position	
  >	
  -­‐1)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  console.log((position)	
  +	
  "	
  seconds");	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  	
  	
  	
  	
  });	
  
},	
  1000);	
  
	
  
function stopAudio() {
            if (media) {
                media.stop();
            }
            clearInterval(myTimer);
            myTimer = null;	

}	
  
Accelerometer
navigator.contacts	
  

A global object that provides access to the device contacts DB

You can call 2 methods on navigator.contacts
•  contacts.create
•  contacts.find

Contacts
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
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
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
Create contact example
var	
  contact	
  =	
  navigator.contacts.create({	
  
	
  displayName:	
  “Ivano“	
  
});	
  
	
  
var	
  name	
  =	
  new	
  ContactName();	
  
name.givenName	
  =	
  “Ivano“;	
  
name.familyName	
  =	
  “Malavolta“;	
  
contact.name	
  =	
  name;	
  
	
  
contact.birthday	
  =	
  new	
  Date(“19	
  July	
  1983);	
  
	
  
contact.save(win,	
  fail);	
  
	
  
function	
  win(contact)	
  {	
  
	
  console.log(Save	
  Success);	
  
};	
  
	
  
function	
  fail(contactError)	
  {	
  
	
  console.log(Error	
  =	
  	
  +	
  contactError.code);	
  
};	
  
	
  
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
Contact fields
Specifies which fields should be included in the Contact objects resulting from a find
operation
var	
  fields	
  =	
  [displayName,	
  name];	
  //	
  or	
  [“*”]	
  
navigator.contacts.find(fields,	
  win,	
  fail);	
  
function	
  win(contacts)	
  {	
  
	
  console.log(‘ok');	
  
};	
  
function	
  fail(err)	
  {	
  
	
  	
  console.log(err.code);	
  
};	
  
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
Contact Error
Encapsulates the error code resulting from a failed lookup operation in the contacts DB

It contains a pre-defined error code
ContactError.UNKNOWN_ERROR
ContactError.INVALID_ARGUMENT_ERROR
ContactError.TIMEOUT_ERROR
ContactError.PENDING_OPERATION_ERROR
ContactError.IO_ERROR
ContactError.NOT_SUPPORTED_ERROR
ContactError.PERMISSION_DENIED_ERROR
Contact find example
var	
  options	
  =	
  new	
  ContactFindOptions();	
  
options.filter	
  =	
  “Ivano;	
  
options.multiple	
  =	
  true;	
  
	
  
filter	
  =	
  [displayName,“birthday];	
  
	
  
navigator.contacts.find(filter,	
  win,	
  fail,	
  options);	
  
	
  
function	
  win(contacts)	
  {	
  
	
  for	
  (var	
  i=0;	
  icontacts.length;	
  i++)	
  {	
  
	
   	
  console.log(contacts[i].displayName);	
  
	
  }	
  
};	
  
	
  
function	
  fail(contactError)	
  {	
  
	
  console.log(Error	
  =	
  	
  +	
  contactError.code);	
  
};	
  
	
  
Accelerometer
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

Connection
Connection.type
Encapsulates the error code resulting from a failed lookup operation in the contacts DB

Values:
Connection.UNKNOWN
Connection.ETHERNET
Connection.WIFI
Connection.CELL_2G
Connection.CELL_3G
Connection.CELL_4G
Connection.CELL
Connection.NONE
iOS can't detect the type of cellular network
connection, it will return always Connection.CELL_2G
Accelerometer
window.device	
  

Contains information about the device’s hardware and software

It is assigned to the window global object	
  
Device information
Device properties
A device object provides the following properties:

device.model

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.)
http://theiphonewiki.com/wiki/Models
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


device.version 

the OS version of the device (ex. “4.1”, “2.2”, etc.)
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 information example
function	
  getDeviceInfo()	
  {	
  
	
  var	
  element	
  =	
  document.getElementById('deviceProperties');	
  
	
  	
  	
  element.innerHTML	
  =	
  'Device	
  Model:	
  '	
  	
  	
  	
  +	
  device.model	
  	
  	
  	
  +	
  'br	
  /'	
  +	
  
	
  	
  	
  	
  	
   	
   	
   	
   	
   	
  'Device	
  Cordova:	
  '	
  	
  +	
  device.cordova	
  	
  +	
  'br	
  /'	
  +	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  'Device	
  Platform:	
  '	
  +	
  device.platform	
  +	
  'br	
  /'	
  +	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  'Device	
  UUID:	
  '	
  	
  	
  	
  	
  +	
  device.uuid	
  	
  	
  	
  	
  +	
  'br	
  /'	
  +	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  'Device	
  Version:	
  '	
  	
  +	
  device.version	
  	
  +	
  'br	
  /';	
  
	
  }	
  
Accelerometer
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);	
  

Events
Cordova events
•  deviceready
•  pause, resume
•  online, offline
•  batterycritical, batterylow, batterystatus
•  backbutton, menubutton, searchbutton
•  startcallbutton, endcallbutton
•  volumedownbutton, volumeupbutton
these work on Blackberry 10 only
Android buttons events
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
App lifecycle events
Based on two main events:

pause

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
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.
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)
Battery events
Based on two main events:

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
This value is device-specific
The battery status must
change of at least 1%
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
Accelerometer

Allows yout to provide feedback to the user
•  alert
•  confirm
•  prompt
•  beep
•  vibrate
Notifications
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”)
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”)
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
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
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
END
What is not covered in this lecture
•  Cordova Native Platform Dev workflow  Plugman
•  Cordova’s secondary APIs:
•  Splashscreen, InAppBrowser, Globalization
•  Geolocalization
•  Local storage  File API
•  PhoneGap Build 
•  How to develop a plugin
We will have dedicated
lectures on these
References
http://cordova.apache.org/docs/en/3.4.0
+ 39 380 70 21 600
Contact
Ivano Malavolta | 
Gran Sasso Science Institute

iivanoo
ivano.malavolta@univaq.it
www.ivanomalavolta.com

Más contenido relacionado

La actualidad más candente

Android animation
Android animationAndroid animation
Android animation
Krazy Koder
 
Android resource
Android resourceAndroid resource
Android resource
Krazy Koder
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
洪 鹏发
 

La actualidad más candente (20)

Android SDK Tutorial | Edureka
Android SDK Tutorial | EdurekaAndroid SDK Tutorial | Edureka
Android SDK Tutorial | Edureka
 
Mobile Web Apps
Mobile Web AppsMobile Web Apps
Mobile Web Apps
 
Top 11 Mobile App Development Frameworks
Top 11 Mobile App Development FrameworksTop 11 Mobile App Development Frameworks
Top 11 Mobile App Development Frameworks
 
Android animation
Android animationAndroid animation
Android animation
 
AEM & Single Page Applications (SPAs) 101
AEM & Single Page Applications (SPAs) 101AEM & Single Page Applications (SPAs) 101
AEM & Single Page Applications (SPAs) 101
 
Flutter
FlutterFlutter
Flutter
 
Publishing and delivery of mobile application
Publishing and delivery of mobile applicationPublishing and delivery of mobile application
Publishing and delivery of mobile application
 
Ionic Framework
Ionic FrameworkIonic Framework
Ionic Framework
 
React workshop presentation
React workshop presentationReact workshop presentation
React workshop presentation
 
Building an Android app with Jetpack Compose and Firebase
Building an Android app with Jetpack Compose and FirebaseBuilding an Android app with Jetpack Compose and Firebase
Building an Android app with Jetpack Compose and Firebase
 
Android UI
Android UIAndroid UI
Android UI
 
Android resource
Android resourceAndroid resource
Android resource
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
Project meeting: Android Graphics Architecture Overview
Project meeting: Android Graphics Architecture OverviewProject meeting: Android Graphics Architecture Overview
Project meeting: Android Graphics Architecture Overview
 
Introduction to flutter's basic concepts
Introduction to flutter's basic conceptsIntroduction to flutter's basic concepts
Introduction to flutter's basic concepts
 
Telephony API
Telephony APITelephony API
Telephony API
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
Flutter vs xamarin vs react native - Mobile App Development Framework
Flutter vs xamarin vs react native - Mobile App Development FrameworkFlutter vs xamarin vs react native - Mobile App Development Framework
Flutter vs xamarin vs react native - Mobile App Development Framework
 
AndroidManifest
AndroidManifestAndroidManifest
AndroidManifest
 
Mobile application development
Mobile application developmentMobile application development
Mobile application development
 

Destacado

6039317 ebanking
6039317 ebanking6039317 ebanking
6039317 ebanking
Sanjiv Shet
 
Cross Platform Mobile Application Architecture
Cross Platform Mobile Application ArchitectureCross Platform Mobile Application Architecture
Cross Platform Mobile Application Architecture
Derrick Bowen
 

Destacado (20)

Cordova / PhoneGap, mobile apps development with HTML5/JS/CSS
Cordova / PhoneGap, mobile apps development with HTML5/JS/CSSCordova / PhoneGap, mobile apps development with HTML5/JS/CSS
Cordova / PhoneGap, mobile apps development with HTML5/JS/CSS
 
Apps with Apache Cordova and Phonegap
Apps with Apache Cordova and PhonegapApps with Apache Cordova and Phonegap
Apps with Apache Cordova and Phonegap
 
Cordova: APIs and instruments
Cordova: APIs and instrumentsCordova: APIs and instruments
Cordova: APIs and instruments
 
Cordova and PhoneGap Insights
Cordova and PhoneGap InsightsCordova and PhoneGap Insights
Cordova and PhoneGap Insights
 
Apache Cordova 3.3 de zéro
Apache Cordova 3.3 de zéroApache Cordova 3.3 de zéro
Apache Cordova 3.3 de zéro
 
Testes com xUnit + Coding Dojo
Testes com xUnit + Coding DojoTestes com xUnit + Coding Dojo
Testes com xUnit + Coding Dojo
 
Desenvolvimento Cross-Mobile com Xamarin
Desenvolvimento Cross-Mobile com Xamarin Desenvolvimento Cross-Mobile com Xamarin
Desenvolvimento Cross-Mobile com Xamarin
 
C# 7 em 7 minutos
C# 7 em 7 minutosC# 7 em 7 minutos
C# 7 em 7 minutos
 
Ebanking
EbankingEbanking
Ebanking
 
Phonegap/Cordova vs Native Application
Phonegap/Cordova vs Native ApplicationPhonegap/Cordova vs Native Application
Phonegap/Cordova vs Native Application
 
6039317 ebanking
6039317 ebanking6039317 ebanking
6039317 ebanking
 
[2015/2016] Apache Cordova
[2015/2016] Apache Cordova[2015/2016] Apache Cordova
[2015/2016] Apache Cordova
 
Desenvolvimento Mobile: Híbrido x Nativo
Desenvolvimento Mobile: Híbrido x NativoDesenvolvimento Mobile: Híbrido x Nativo
Desenvolvimento Mobile: Híbrido x Nativo
 
Implement server push in flask framework
Implement server push in flask frameworkImplement server push in flask framework
Implement server push in flask framework
 
All About Phonegap
All About Phonegap All About Phonegap
All About Phonegap
 
Cross Platform Mobile Application Architecture
Cross Platform Mobile Application ArchitectureCross Platform Mobile Application Architecture
Cross Platform Mobile Application Architecture
 
Hybrid Apps with Ionic Framework
Hybrid Apps with Ionic FrameworkHybrid Apps with Ionic Framework
Hybrid Apps with Ionic Framework
 
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
 
Cordova + Ionic + MobileFirst
Cordova + Ionic + MobileFirstCordova + Ionic + MobileFirst
Cordova + Ionic + MobileFirst
 
Hybrid app development with ionic
Hybrid app development with ionicHybrid app development with ionic
Hybrid app development with ionic
 

Similar a Apache Cordova

Cross-Platform Development using Angulr JS in Visual Studio
Cross-Platform Development using Angulr JS in Visual StudioCross-Platform Development using Angulr JS in Visual Studio
Cross-Platform Development using Angulr JS in Visual Studio
Mizanur Sarker
 
Hybrid Mobile Development with Apache Cordova and
Hybrid Mobile Development with Apache Cordova and Hybrid Mobile Development with Apache Cordova and
Hybrid Mobile Development with Apache Cordova and
Ryan Cuprak
 

Similar a Apache Cordova (20)

Apache Cordova 4.x
Apache Cordova 4.xApache Cordova 4.x
Apache Cordova 4.x
 
Apache cordova
Apache cordovaApache cordova
Apache cordova
 
Cordova Tutorial
Cordova TutorialCordova Tutorial
Cordova Tutorial
 
Cross-Platform Development using Angulr JS in Visual Studio
Cross-Platform Development using Angulr JS in Visual StudioCross-Platform Development using Angulr JS in Visual Studio
Cross-Platform Development using Angulr JS in Visual Studio
 
Apache Cordova phonegap plugins for mobile app development
Apache Cordova phonegap plugins for mobile app developmentApache Cordova phonegap plugins for mobile app development
Apache Cordova phonegap plugins for mobile app development
 
NCDevCon 2017 - Cross Platform Mobile Apps
NCDevCon 2017 - Cross Platform Mobile AppsNCDevCon 2017 - Cross Platform Mobile Apps
NCDevCon 2017 - Cross Platform Mobile Apps
 
Hybrid Mobile Applications
Hybrid Mobile ApplicationsHybrid Mobile Applications
Hybrid Mobile Applications
 
Cross-platform Mobile Development on Open Source
Cross-platform Mobile Development on Open SourceCross-platform Mobile Development on Open Source
Cross-platform Mobile Development on Open Source
 
Intro to PhoneGap
Intro to PhoneGapIntro to PhoneGap
Intro to PhoneGap
 
Hybrid Mobile Development with Apache Cordova and
Hybrid Mobile Development with Apache Cordova and Hybrid Mobile Development with Apache Cordova and
Hybrid Mobile Development with Apache Cordova and
 
Exploring pwa for shopware
Exploring pwa for shopwareExploring pwa for shopware
Exploring pwa for shopware
 
Developing Windows Phone 8 apps using PhoneGap
Developing Windows Phone 8 apps using PhoneGapDeveloping Windows Phone 8 apps using PhoneGap
Developing Windows Phone 8 apps using PhoneGap
 
Introduction phonegap
Introduction phonegapIntroduction phonegap
Introduction phonegap
 
Advanced programing in phonegap
Advanced programing in phonegapAdvanced programing in phonegap
Advanced programing in phonegap
 
HTML5: the new frontier of the web
HTML5: the new frontier of the webHTML5: the new frontier of the web
HTML5: the new frontier of the web
 
Android - Anroid Pproject
Android - Anroid PprojectAndroid - Anroid Pproject
Android - Anroid Pproject
 
Adobe AIR Programming to Desktop and Mobile
Adobe AIR Programming to Desktop and MobileAdobe AIR Programming to Desktop and Mobile
Adobe AIR Programming to Desktop and Mobile
 
iOS Application Security
iOS Application SecurityiOS Application Security
iOS Application Security
 
Droidcon uk2012 androvm
Droidcon uk2012 androvmDroidcon uk2012 androvm
Droidcon uk2012 androvm
 
Cross Platform Mobile App Development
Cross Platform Mobile App DevelopmentCross Platform Mobile App Development
Cross Platform Mobile App Development
 

Más de Ivano Malavolta

Más de Ivano Malavolta (20)

Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
 
The H2020 experience
The H2020 experienceThe H2020 experience
The H2020 experience
 
The Green Lab - Research cocktail @Vrije Universiteit Amsterdam (October 2020)
The Green Lab - Research cocktail  @Vrije Universiteit Amsterdam (October 2020)The Green Lab - Research cocktail  @Vrije Universiteit Amsterdam (October 2020)
The Green Lab - Research cocktail @Vrije Universiteit Amsterdam (October 2020)
 
Software sustainability and Green IT
Software sustainability and Green ITSoftware sustainability and Green IT
Software sustainability and Green IT
 
Navigation-aware and Personalized Prefetching of Network Requests in Android ...
Navigation-aware and Personalized Prefetching of Network Requests in Android ...Navigation-aware and Personalized Prefetching of Network Requests in Android ...
Navigation-aware and Personalized Prefetching of Network Requests in Android ...
 
How Maintainability Issues of Android Apps Evolve [ICSME 2018]
How Maintainability Issues of Android Apps Evolve [ICSME 2018]How Maintainability Issues of Android Apps Evolve [ICSME 2018]
How Maintainability Issues of Android Apps Evolve [ICSME 2018]
 
Collaborative Model-Driven Software Engineering: a Classification Framework a...
Collaborative Model-Driven Software Engineering: a Classification Framework a...Collaborative Model-Driven Software Engineering: a Classification Framework a...
Collaborative Model-Driven Software Engineering: a Classification Framework a...
 
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
 
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
 
Modeling behaviour via UML state machines [Software Design] [Computer Science...
Modeling behaviour via UML state machines [Software Design] [Computer Science...Modeling behaviour via UML state machines [Software Design] [Computer Science...
Modeling behaviour via UML state machines [Software Design] [Computer Science...
 
Object-oriented design patterns in UML [Software Design] [Computer Science] [...
Object-oriented design patterns in UML [Software Design] [Computer Science] [...Object-oriented design patterns in UML [Software Design] [Computer Science] [...
Object-oriented design patterns in UML [Software Design] [Computer Science] [...
 
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
 
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
 
Modeling and abstraction, software development process [Software Design] [Com...
Modeling and abstraction, software development process [Software Design] [Com...Modeling and abstraction, software development process [Software Design] [Com...
Modeling and abstraction, software development process [Software Design] [Com...
 
[2017/2018] Agile development
[2017/2018] Agile development[2017/2018] Agile development
[2017/2018] Agile development
 
Reconstructing microservice-based architectures
Reconstructing microservice-based architecturesReconstructing microservice-based architectures
Reconstructing microservice-based architectures
 
[2017/2018] AADL - Architecture Analysis and Design Language
[2017/2018] AADL - Architecture Analysis and Design Language[2017/2018] AADL - Architecture Analysis and Design Language
[2017/2018] AADL - Architecture Analysis and Design Language
 
[2017/2018] Architectural languages
[2017/2018] Architectural languages[2017/2018] Architectural languages
[2017/2018] Architectural languages
 
[2017/2018] Introduction to Software Architecture
[2017/2018] Introduction to Software Architecture[2017/2018] Introduction to Software Architecture
[2017/2018] Introduction to Software Architecture
 
[2017/2018] RESEARCH in software engineering
[2017/2018] RESEARCH in software engineering[2017/2018] RESEARCH in software engineering
[2017/2018] RESEARCH in software engineering
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Apache Cordova

  • 1. Gran Sasso Science Institute Ivano Malavolta Apache Cordova
  • 2. Roadmap •  The Cordova framework •  Recurrent app architecture •  Cordova CLI •  Debugging Cordova applications •  My development environment •  Cordova APIs
  • 3. PhoneGap VS Cordova Adobe/Nitobi donated the PhoneGap codebase to the Apache foundation à wider audience and contributors à transparent governance Better documentation à easier contributions for companies Apache Licensing There was only one problem.... trademark ambiguity à CORDOVA PhoneGap is a distribution of Apache Cordova
  • 4. Cordova 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/
  • 5. Cordova The UI layer is a web browser view •  100% width •  100% height Headless web browser •  No URL bar •  No decorations •  No zooming •  No text selection
  • 6. Can I use HTML5, JS and CSS libraries I use everyday?
  • 9. When Cordova API is not enough... Sometimes Cordova is not enough as is for our purposes •  unsupported feature •  heavyweight data processing is faster in native code ex. images manipulation •  background processing is better handled natively ex. files sync •  complex business logic à You can develop a Cordova plugin
  • 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 Plugins are installed and removed using the Cordova CLI instrument Developers Can compose a version of Cordova suited to their project needs Cordova contributors Can revision APIs independently + it is easier to upgrade and extend APIs Users Smaller and faster apps
  • 12. Cordova plugin architecture Cordova core is now composed of 17 repos Comparing it to the old plugin architecture... http://phonegap.com/blog/2013/06/20/coming-soon-phonegap30/
  • 13. Examples of available plugins Please, notice the upload dates J
  • 14. Roadmap •  The Cordova framework •  Recurrent app architecture •  Cordova CLI •  Debugging Cordova applications •  My development environment •  Cordova APIs
  • 15. Recurrent app architecture The app acts as a client for user interaction The app communicates with an application server to receive data The application server handles business logic and communicates with a back-end data repository App Application server 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
  • 19. Roadmap •  The Cordova framework •  Recurrent app architecture •  Cordova CLI •  Debugging Cordova applications •  My development environment •  Cordova APIs
  • 20. Cordova CLI 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 CLI = Command-Line Interface If you prefer to use platform- specific SDKs, you can still use it to initialize your project
  • 21. Creates template project •  PATH the folder that will contain your project •  ID package identifier in reverse-domain style (optional) •  NAME display name of the app (optional) Project creation
  • 22. The create command creates a predefined project structure •  merges a mirror of the www folder containing platform-specific assets •  platforms platform specific projects (ex. an Eclipse project for Android, XCode for iOS) •  plugins installed plugins (both JS files and native resources) •  www contains your HTML, JS, CSS files Project structure config.xml contains core Cordova API features, plugins, and platform-specific settings. See here for the iOS values: http://goo.gl/1CcmyL
  • 23. 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   •  PLATFORM_NAME the name of the platform (e.g., ios, android, wp8) Add platforms If you do something like this: cordova  platform  remove  ios   you are removing a specific platform You can use an SDK such as Eclipse or Xcode to open the project you created
  • 24. 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) Build the app If you do not specify the PLATFORM_NAME, Cordova will build for all installed platforms
  • 25. 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) emulate/run the app
  • 26. 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 add plugins If you do something like this: cordova  plugin  remove  PLUGIN_NAME   you are removing a specific plugin The list of plugins can be found here http://plugins.cordova.io 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
  • 27. 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 Platform custom code
  • 28. Roadmap •  The Cordova framework •  Recurrent app architecture •  Cordova CLI •  Debugging Cordova applications •  My development environment •  Cordova APIs
  • 29. The killer app! •  Check console •  Breakpoints •  Update the DOM at run-time •  Access to all local DBs •  Network profiling •  CPU and memory profiling •  Monitor event listeners •  Monitor elements’ rendering time
  • 30. Desktop Browser •  very quick •  very handy functions •  see Chrome’s Web Development Tools •  Breakpoints PRO •  browsers’ small differences and bugs •  cannot test all Cordova’s specific functionalities •  you need Phonegap shims CONS
  • 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!
  • 33. Desktop Browser - Tools Browser’s extension for window dimensions Resolution Test http://goo.gl/fQpbH PhoneGap Shims, there are many, this is the most used: PhoneGap-Desktop https://github.com/jxp/phonegap-desktop
  • 34. Ripple •  very quick •  can use Chrome’s Web Development Tools •  You can test Cordova’s API from the Desktop •  browsers’ small differences and bugs •  cannot test the interaction with external apps PRO CONS It is based on Ripple, a Chrome plugin for mobile dev from Cordova 3.0.0, you need to use the Ripple available at Apache npm  install  -­‐g  ripple-­‐emulator   ripple  emulate  
  • 36. Simulator •  Officially supported by platform vendors •  You use the “real” device’s browser PRO •  device’s performance is not considered •  this is iOS-specific •  Android’s emulator is a joke •  device’s capabilities are only simulated CONS
  • 37. On device •  accurate •  still handy •  real performance tests •  real browser tests PRO •  Deployment takes some time (~6 seconds for iOS) CONS
  • 38. Remote Debugging 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 Since Android 4.4, this feature is available via Chrome’s web dev kit
  • 39. Remote Debugging for older platforms Weinre http://people.apache.org/~pmuellr/weinre/docs/latest/ 3 main components: Debug Server the HTTP server for debug data Debug Target the (web) app you are debugging Debug Client the Web Inspector user interface Public debug server: debug.phonegap.com
  • 40. Debugging reference table Make a favor to yourself, don’t debug craftsman way: console.log()  +  alert()   iOS Android Desktop Browser Ripple Device/emulator Weinre Safari Web Inspector X Chrome Web Inspector X
  • 41. Roadmap •  The Cordova framework •  Recurrent app architecture •  Cordova CLI •  Debugging Cordova applications •  My development environment and workflow •  Cordova APIs
  • 42. My development environment Sublime Text 2 http://www.sublimetext.com SublimeText Package Control http://wbond.net/sublime_packages/package_control Sidebar Enhancer https://github.com/titoBouzout/SideBarEnhancements HTML Prettify https://github.com/victorporof/Sublime-HTMLPrettify SublimeLinter https://github.com/SublimeLinter/SublimeLinter JsFormat https://github.com/jdc0589/JsFormat
  • 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
  • 45. Roadmap •  The Cordova framework •  Recurrent app architecture •  Cordova CLI •  Debugging Cordova applications •  My development environment •  Cordova APIs •  Accelerometer •  Compass •  Capturing audio and video & camera •  Media playback •  Contacts •  Connection •  Device information •  Events •  Notification
  • 46. 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   Accelerometer
  • 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  
  • 49. clearWatch clearWatch(watchID);   Stop watching the Acceleration referenced by the watch ID parameter watchID ID returned by accelerometer.watchAcceleration
  • 50. The Acceleration object It contains accelerometer data captured at a specific point in time 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 these values include the effect of gravity (9.81 m/s^2)
  • 51. Accelerometer example var  options  =  {  frequency:  3000  };   var  watchID  =  navigator.accelerometer.watchAcceleration(win,  fail,  options);     function  win(acc)  {    if((acc.x  ==  0)  &&  (acc.y  ==  0)  &&  (acc.z  ==  9,81))    {      console.log(“I  am  on  a  table”);      stop();    }  else  {      console.log(“Please,  leave  me  on  the  table”);    }   }   function  fail()  {    console.log(“error”);   }     function  stop()  {    if(watchID)  {      navigator.accelerometer.clearWatch(watchID);      watchID  =  null;    }   }    
  • 52. Shake detection var  previousReading  =  {x:  null,  y:  null,  z:  null};     navigator.accelerometer.watchAcceleration(function  (reading)  {    var  changes  =  {},    threshold  =  30;    if  (previousReading.x  !==  null)  {      changes.x  =  Math.abs(previousReading.x,  reading.x);      changes.y  =  Math.abs(previousReading.y,  reading.y);      changes.z  =  Math.abs(previousReading.z,  reading.z);    }    if  (changes.x  +  changes.y  +  changes.z  >  (threshold  *  3))  {      console.log(“shake  detected”);    }    previousReading  =  {      x:  reading.x,      y:  reading.y,      z:  reading.z    }   },  errorCallback,  {  frequency:  300  });  
  • 53. Accelerometer navigator.device.capture   Provides access for capturing directly from the device   Audio Image Video Capturing Audio and Video Omogeneous APIs between audio, image, and video capturing based on a W3C specification
  • 54. Supported formats The navigator.device.capture  object contains 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 They all contain an array of ConfigurationData objects
  • 55. The ConfigurationData object It is used to describe media capture modes supported by the device Properties  type (String) the string in lower case representing the media type height (Number) the height of the image or video in pixels width (Number) the height of the image or video in pixels ex. •  video/3gpp •  video/quicktime •  image/jpeg •  audio/amr •  audio/wav
  • 56. Supported format example var  imageModes  =  navigator.device.capture.supportedImageModes;                          for(var  i=0;  i  <imageModes.length;  i++)  {                                  var  mode  =  imageModes[i];                                  console.log(mode.type);                                  console.log(mode.height);                                  console.log(mode.width);                          }  
  • 57. Audio capture captureAudio(win,  [fail],  [options]);   Starts the audio recorder app and returns information about captured audio clip files win callback function with an array of MediaFile parameter fail error or when the users cancels the capture operation before capturing any media file options audio capture options It uses the device's default audio recording app The operation allows the device user to capture multiple recordings in a single session
  • 58. Options limit (Number) the maximum number of audio clips the user can record in a single capture operation duration (Number) the maximum duration of an audio sound clip, in seconds not supported in iOS not supported in Android
  • 59. Audio capture example var  options  =  {  limit:  2,  duration:  5  };     navigator.device.capture.captureAudio(win,  fail,  options);     function  win(mediaFiles)  {    var  i;    for  (i=0;  i<mediaFiles.length;  i++)  {      console.log(mediaFiles[i]);    }               }     function  fail(error)  {    console.log(‘Error  with  code:  '  +  error.code);   }  
  • 60. 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 fail error or when the users cancels the capture operation before capturing any media file options image capture options It uses the device's default camera app The operation allows the device user to capture multiple images in a single session
  • 61. Options limit (Number) the maximum number of photos the user can take in a single capture operation not supported in iOS
  • 62. 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 fail error or when the users cancels the capture operation before capturing any media file options video capture options It uses the device's default camera app The operation allows the device user to capture multiple videos in a single session
  • 63. Options limit (Number) the maximum number of videos the user can take in a single capture operation duration (Number) the maximum duration of each video, in seconds not supported in iOS
  • 64. 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
  • 65. 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
  • 66. 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)
  • 67. Capture Error Encapsulates the error code resulting from a failed media capture operation It contains a pre-defined error code CaptureError.CAPTURE_INTERNAL_ERR CaptureError.CAPTURE_APPLICATION_BUSY CaptureError.CAPTURE_INVALID_ARGUMENT CaptureError.CAPTURE_NO_MEDIA_FILES CaptureError.CAPTURE_NOT__SUPPORTED
  • 68. 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
  • 69. Getting pictures from the camera 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
  • 70. getPicture options getPicture() can be called with the following options
  • 71. getPicture options quality (Number) quality of saved image Range [0, 100] allowEdit (boolean) allow simple editing of the image before selection destinationType (Number)
  • 73. getPicture options mediaType (Number) correctOrientation (boolean) Rotate the image to correct for the orientation of the device during capture
  • 74. getPicture options saveToPhotoAlbum (boolean) Save the image to the photo album on the device after capture popoverOptions (object) iPad only
  • 75. getPicture options targetWidth, targetHeight (Number) width/height in pixels to scale image cameraDirection (Number)
  • 76. Camera cleanup camera.cleanup(win,  [fail]);   Removes intermediate photos taken by the camera from temporary storage win callback function fail error callback Valid only when •  the value of Camera.sourceType === Camera.PictureSourceType.CAMERA •  the Camera.destinationType === Camera.DestinationType.FILE_URI iOS only
  • 77. Camera example var  options  =  {  quality:  50,    destinationType:  destinationType.FILE_URI,    sourceType:  pictureSource.PHOTOLIBRARY     });     navigator.camera.getPicture(win,  fail,  options);     function  win(imageURI)  {    var  element  =  $(“#block”);    element.src(imageURI);   }     function  fail  (error)  {    console.log(error);  //  this  is  provided  by  the  device’s  native  code   }  
  • 78. Accelerometer Media   The Media object provides the ability to record and play back audio files on a device Media playback It does not adhere to any W3C specification, it is just a convenience API provided by Cordova
  • 79. The Media object var  media  =  new  Media(src,  win,  [fail],  [status]);   src (String): A URI containing the audio content The URI can be local or can be a URL addressable by a standard HTTP get request win: callback executed when the object executes a play, record, or stop action fail: error callback status: callback executed to indicate status changes Media status possible parameters: •  Media.MEDIA_NONE = 0; •  Media.MEDIA_STARTING = 1; •  Media.MEDIA_RUNNING = 2; •  Media.MEDIA_PAUSED = 3; •  Media.MEDIA_STOPPED = 4;
  • 81. Media Error Encapsulates the error code resulting from a failed media operation It contains a pre-defined error code MediaError.MEDIA_ERR_ABORTED MediaError.MEDIA_ERR_NETWORK MediaError.MEDIA_ERR_DECODE MediaError.MEDIA_ERR_NONE_SUPPORTED
  • 82. Media example var  media  =  new  Media(“http://path/to/mp3”,  win,  fail);     //  every  second  we  log  the  position   var  myTimer  =  setInterval(function  ()  {    media.getCurrentPosition(      function  (position)  {                          if  (position  >  -­‐1)  {                                  console.log((position)  +  "  seconds");                          }                  });   },  1000);     function stopAudio() {             if (media) {                 media.stop();             }             clearInterval(myTimer);             myTimer = null; }  
  • 83. Accelerometer navigator.contacts   A global object that provides access to the device contacts DB You can call 2 methods on navigator.contacts •  contacts.create •  contacts.find Contacts
  • 84. 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
  • 85. 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
  • 86. 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
  • 87. Create contact example var  contact  =  navigator.contacts.create({    displayName:  “Ivano“   });     var  name  =  new  ContactName();   name.givenName  =  “Ivano“;   name.familyName  =  “Malavolta“;   contact.name  =  name;     contact.birthday  =  new  Date(“19  July  1983);     contact.save(win,  fail);     function  win(contact)  {    console.log(Save  Success);   };     function  fail(contactError)  {    console.log(Error  =    +  contactError.code);   };    
  • 88. 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
  • 89. Contact fields Specifies which fields should be included in the Contact objects resulting from a find operation var  fields  =  [displayName,  name];  //  or  [“*”]   navigator.contacts.find(fields,  win,  fail);   function  win(contacts)  {    console.log(‘ok');   };   function  fail(err)  {      console.log(err.code);   };  
  • 90. 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
  • 91. Contact Error Encapsulates the error code resulting from a failed lookup operation in the contacts DB It contains a pre-defined error code ContactError.UNKNOWN_ERROR ContactError.INVALID_ARGUMENT_ERROR ContactError.TIMEOUT_ERROR ContactError.PENDING_OPERATION_ERROR ContactError.IO_ERROR ContactError.NOT_SUPPORTED_ERROR ContactError.PERMISSION_DENIED_ERROR
  • 92. Contact find example var  options  =  new  ContactFindOptions();   options.filter  =  “Ivano;   options.multiple  =  true;     filter  =  [displayName,“birthday];     navigator.contacts.find(filter,  win,  fail,  options);     function  win(contacts)  {    for  (var  i=0;  icontacts.length;  i++)  {      console.log(contacts[i].displayName);    }   };     function  fail(contactError)  {    console.log(Error  =    +  contactError.code);   };    
  • 93. Accelerometer 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 Connection
  • 94. Connection.type Encapsulates the error code resulting from a failed lookup operation in the contacts DB Values: Connection.UNKNOWN Connection.ETHERNET Connection.WIFI Connection.CELL_2G Connection.CELL_3G Connection.CELL_4G Connection.CELL Connection.NONE iOS can't detect the type of cellular network connection, it will return always Connection.CELL_2G
  • 95. Accelerometer window.device   Contains information about the device’s hardware and software It is assigned to the window global object   Device information
  • 96. Device properties A device object provides the following properties: device.model 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.) http://theiphonewiki.com/wiki/Models
  • 97. 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 device.version the OS version of the device (ex. “4.1”, “2.2”, etc.) in iOS it is not reliable: The uuid on iOS is not unique to a device, but varies for each application, for each installation
  • 98. Device information example function  getDeviceInfo()  {    var  element  =  document.getElementById('deviceProperties');        element.innerHTML  =  'Device  Model:  '        +  device.model        +  'br  /'  +                      'Device  Cordova:  '    +  device.cordova    +  'br  /'  +                                                'Device  Platform:  '  +  device.platform  +  'br  /'  +                                                'Device  UUID:  '          +  device.uuid          +  'br  /'  +                                                'Device  Version:  '    +  device.version    +  'br  /';    }  
  • 99. Accelerometer 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);   Events
  • 100. Cordova events •  deviceready •  pause, resume •  online, offline •  batterycritical, batterylow, batterystatus •  backbutton, menubutton, searchbutton •  startcallbutton, endcallbutton •  volumedownbutton, volumeupbutton these work on Blackberry 10 only Android buttons events
  • 101. 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
  • 102. App lifecycle events Based on two main events: pause 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 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.
  • 103. 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)
  • 104. Battery events Based on two main events: 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 This value is device-specific The battery status must change of at least 1%
  • 105. 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
  • 106. Accelerometer Allows yout to provide feedback to the user •  alert •  confirm •  prompt •  beep •  vibrate Notifications
  • 107. 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”)
  • 108. 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”)
  • 109. 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
  • 110. 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
  • 111. 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
  • 112. END
  • 113. What is not covered in this lecture •  Cordova Native Platform Dev workflow Plugman •  Cordova’s secondary APIs: •  Splashscreen, InAppBrowser, Globalization •  Geolocalization •  Local storage File API •  PhoneGap Build •  How to develop a plugin We will have dedicated lectures on these
  • 115. + 39 380 70 21 600 Contact Ivano Malavolta | Gran Sasso Science Institute iivanoo ivano.malavolta@univaq.it www.ivanomalavolta.com