Share
Embed
PhoneGap Deep Dive
PhoneGap is an open-source framework (Apache Cordova) that allows you to create cross-platform mobile apps using the web technologies you know and love: HTML, CSS, and JavaScript. Learn how PhoneGap works and how it will enable you to start building mobile apps with web standards. This talk will take a closer look at some of the available APIs and how further extend PhoneGap through the use of it's plugin system.
Chris Griffith
July 17, 2013
Transcript
64 slides
-
These opinions and thoughts are my own, and may
or may not reflect the opinions of the company that I work for. Disclaimer -
ApplicaAon container that allows you to build naAvely installed
apps using HTML, CSS & JavaScript What is PhoneGap? -
• Accelerometer -‐ when the device moves • Camera
-‐ pictures of your cat • Capture -‐ audio, video, sAlls of your cat • Compass -‐ for when you're lost • Connec<on -‐ type of connecAon • Contacts -‐ find and create new friends Features -
• Device -‐ device and OS version metadata •
Events -‐ various app/hardware related events • File -‐ naAve file system access (+ upload) • Geoloca<on -‐ for when you're lost • Globaliza<on -‐ date/number/currency formaRng Features -
• Media -‐ related to audio playback (supports record
as well) • No<fica<on -‐ visual, audible, and tacAle noAficaAons • Splashscreen -‐ for your splash screen needs • Storage -‐ Mini database Features -
<!DOCTYPE html> <html> <head> <title>PhoneGap Example</title> <script src="phonegap.js"></script> <script> //
Wait for PhoneGap to load document.addEventListener("deviceready", onDeviceReady, false); -
// PhoneGap is ready function onDeviceReady() { var element =
document.getElementById('deviceProperties'); element.innerHTML = 'Device Name: ' + device.name + '<br />' + 'Device Cordova: ' + device.cordova + '<br />' + 'Device Platform: ' + device.platform + '<br />' + 'Device UUID: ' + device.uuid + '<br />' + 'Device Model: ' + device.model + '<br />' + 'Device Version: ' + device.version + '<br />'; } </script> </head> <body> <p id="deviceProperties">Loading device properties...</p> </body> </html> -
Connec<on The connecAon object gives access to the device's
cellular and wifi connecAon informaAon. ConnecAon.UNKNOWN ConnecAon.ETHERNET ConnecAon.WIFI ConnecAon.CELL_2G ConnecAon.CELL_3G ConnecAon.CELL_4G ConnecAon.CELL ConnecAon.NONE -
function checkConnection() { var networkState = navigator.connection.type; var states =
{}; states[Connection.UNKNOWN] = 'Unknown connection'; states[Connection.ETHERNET] = 'Ethernet connection'; states[Connection.WIFI] = 'WiFi connection'; states[Connection.CELL_2G] = 'Cell 2G connection'; states[Connection.CELL_3G] = 'Cell 3G connection'; states[Connection.CELL_4G] = 'Cell 4G connection'; states[Connection.CELL] = 'Cell generic connection'; states[Connection.NONE] = 'No network connection'; alert('Connection type: ' + states[networkState]); } -
GeolocaAon The geolocaAon object provides access to the
device's GPS sensor. GeolocaAon provides locaAon informaAon for the device, such as laAtude and longitude. Common sources of locaAon informaAon include Global PosiAoning System (GPS) and locaAon inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs. No guarantee is given that the API returns the device's actual locaAon. -
Accuracy Posi<oning Time BaHery Life GPS
10m 2-‐10 minutes (only indoors) 5-‐6 hours on most phones WIFI 50m (improves with density) Almost instant (server connect and lookup) No addiAonal effect Cell Tower triangulaAon 100-‐1400m (based on density) Almost instant (server connect and lookup) Negligible Single Cell Tower 500-‐2500m (based on density) Almost instant (server connect and lookup) Negligible IP Country: 99% City: 46% US, 53% InternaAonal Zip: 0% Almost instant (server connect and lookup) Negligible -
geolocaAon.getCurrentPosiAon Returns the device's current posiAon as a
PosiAon object. navigator.geolocation.getCurrentPosition(geo locationSuccess, [geolocationError], [geolocationOptions]); -
// onSuccess Callback // This method accepts a `Position` object,
which contains // the current GPS coordinates var onSuccess = function(position) { alert('Latitude: ' + position.coords.latitude + '\n' + 'Longitude: ' + position.coords.longitude + '\n' + 'Altitude: ' + position.coords.altitude + '\n' + 'Accuracy: ' + position.coords.accuracy + '\n' + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + 'Heading: ' + position.coords.heading + '\n' + 'Speed: ' + position.coords.speed + '\n' + 'Timestamp: ' + position.timestamp + '\n'); }; // onError Callback receives a PositionError object function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } navigator.geolocation.getCurrentPosition(onSuccess, onError); -
function onDeviceReady() { navigator.compass.getCurrentHeading(onSuccess, onError); } // onSuccess: Get the
current heading function onSuccess(heading) { alert('Heading: ' + heading.magneticHeading); } // onError: Failed to get the heading function onError(compassError) { alert('Compass Error: ' + compassError.code); } -
Accelerometer Captures device moAon in the x, y, and
z direcAon. Methods accelerometer.getCurrentAcceleraAon accelerometer.watchAcceleraAon accelerometer.clearWatch Arguments accelerometerSuccess accelerometerError accelerometerOpAons -
function onSuccess(acceleration) { alert('Acceleration X: ' + acceleration.x + '\n'
+ 'Acceleration Y: ' + acceleration.y + '\n' + 'Acceleration Z: ' + acceleration.z + '\n' + 'Timestamp: ' + acceleration.timestamp + '\n'); }; function onError() { alert('onError!'); }; navigator.accelerometer.getCurrentAcceleration(onS uccess, onError); -
Events • deviceready • pause • resume
• online • offline • backbunon • banerycriAcal • banerylow • banerystatus • menubunon • searchbunon • startcallbunon • endcallbunon • volumedownbunon • volumeupbunon -
document.addEventListener("offline", onOffline, false); function onOffline() { // Handle the offline
event } document.addEventListener("online", onOnline, false); function onOnline() { // Handle the online event } -
Storage Embedded SQLite database or
localStorage -
localStorage Provides access to a W3C Storage interface
(hnp://dev.w3.org/html5/webstorage/#the-‐ localstorage-‐anribute) -
function onDeviceReady() { var element = document.getElementById('localData'); window.localStorage.setItem("key", "value"); var
keyname = window.localStorage.key(i); // keyname is now equal to "key" var value = window.localStorage.getItem("key"); // value is now equal to "value" window.localStorage.removeItem("key"); window.localStorage.setItem("key2", "value2"); element.innerHTML = "Value:"+value; window.localStorage.clear(); // localStorage is now empty } -
Embedded SQLite database var dbShell = window.openDatabase(database_name,
database_version, database_displayname, database_size); -
function populateDB(tx) { tx.executeSql('DROP TABLE IF EXISTS DEMO'); tx.executeSql('CREATE TABLE
IF NOT EXISTS DEMO (id unique, data)'); tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")'); tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")'); } function errorCB(err) { alert("Error processing SQL: "+err); } function successCB() { alert("success!"); } var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000); db.transaction(populateDB, errorCB, successCB); -
Camera The camera object provides access to the
device's default camera applicaAon. -
camera.getPicture Takes a photo using the camera or retrieves
a photo from the device's album. The image is passed to the success callback as a base64 encoded String or as the URI of an image file. -
cameraOpAons { quality : 75, destinationType : Camera.DestinationType.DATA_URL, sourceType
: Camera.PictureSourceType.CAMERA, allowEdit : true, encodingType: Camera.EncodingType.JPEG, targetWidth: 100, targetHeight: 100, popoverOptions: CameraPopoverOptions, saveToPhotoAlbum: false }; -
Capture Provides access to the audio, image, and video
capture capabiliAes of the device. Methods capture.captureAudio: Launch the device audio recording applicaAon for recording audio clip(s). capture.captureImage: Launch the device camera applicaAon for taking image(s). capture.captureVideo: Launch the device video recorder applicaAon for recording video(s). -
capture.captureAudio Start the audio recorder applicaAon and return
informaAon about captured audio clip file(s) -
// capture callback var captureSuccess = function(mediaFiles) { var i,
path, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { path = mediaFiles[i].fullPath; // do something interesting with the file } }; // capture error callback var captureError = function(error) { navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error'); }; // start audio capture navigator.device.capture.captureAudio(captureSuccess , captureError, {limit:2}); -
capture.captureImage // capture callback var captureSuccess = function(mediaFiles) {
var i, path, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { path = mediaFiles[i].fullPath; // do something interesting with the file } }; // capture error callback var captureError = function(error) { navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error'); }; // start image capture navigator.device.capture.captureImage(captureSuccess, captureError, {limit:2}); -
capture.captureVideo Start the video recorder applicaAon and return
informaAon about captured video clip file(s). -
Media The Media object provides the ability to record
and play back audio files on a device. var media = new Media(src, mediaSuccess, [mediaError], [mediaStatus]); -
// Audio player // var my_media = new Media(src, onSuccess,
onError); // Update media position every second var mediaTimer = setInterval(function() { // get media position my_media.getCurrentPosition( // success callback function(position) { if (position > -1) { console.log((position) + " sec"); } }, // error callback function(e) { console.log("Error getting pos=" + e); } ); }, 1000); -
navigator.notification.alert(message, alertCallback, [title], [buttonName]) message: Dialog message (String) alertCallback: Callback
to invoke when alert dialog is dismissed. (Function) title: Dialog title (String) (Optional, Default: "Alert") buttonName: Button name (String) (Optional, Default: "OK") Alert -
// Android / BlackBerry WebWorks (OS 5.0 and higher) /
iPhone / Tizen // function alertDismissed() { // do something } navigator.notification.alert( 'You are the winner!', // message alertDismissed, // callback 'Game Over', // title 'Done' // buttonName ); -
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) message: Dialog message (String) confirmCallback: -
Callback to invoke with index of button pressed (1, 2 or 3) or when the dialog is dismissed without a button press (0), (Function) title: Dialog title (String) (Optional, Default: "Confirm") buttonLabels: Comma separated string with button labels (String) (Optional, Default: "OK,Cancel") Confirm -
// process the confirmation dialog result function onConfirm(buttonIndex) { alert('You
selected button ' + buttonIndex); } // Show a custom confirmation dialog // function showConfirm() { navigator.notification.confirm( 'You are the winner!', // message onConfirm, // callback to invoke with index of button pressed 'Game Over', // title 'Restart,Exit' // buttonLabels ); } -
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels]) message: Dialog message (String) promptCallback: -
Callback to invoke when a button is pressed (Function) title: Dialog title (String) (Optional, Default: "Prompt") buttonLabels: Array of strings for the button labels (Array) (Optional, Default: ["OK","Cancel"]) Prompt -
// process the promp dialog results function onPrompt(results) { alert("You
selected button number " + results.buttonIndex + " and entered " + results.input1); } // Show a custom prompt dialog // function showPrompt() { navigator.notification.prompt( 'Please enter your name', // message onPrompt, // callback to invoke 'Registration', // title ['Ok','Exit'] // buttonLabels ); } -
Android Quirks Android plays the default "NoAficaAon
ringtone" specified under the "SeRngs/Sound & Display" panel. iPhone Quirks Ignores the beep count argument. There is no naAve beep API for iPhone. Cordova implements beep by playing an audio file via the media API. The user must provide a file with the desired beep tone. This file must be less than 30 seconds long, located in the www/ root, and must be named beep.wav. -
The InAppBrowser is a web-‐browser that is shown in your
app when you use the window.open call. ref.addEventListener(eventname, callback); loadstart - event fired when the InAppBrowser starts to load a URL loadstop - event fired when the InAppBrowser finished loading a URL loaderror - event fired when the InAppBrowser encounters an error loading a URL exit - event fired when the InAppBrowser window is closed InAppBrowser