137

Develop, test and debug cross platforms apps with PhoneGap

Embed Size (px)

Citation preview

Page 1: Develop, test and debug cross platforms apps with PhoneGap
Page 2: Develop, test and debug cross platforms apps with PhoneGap
Page 3: Develop, test and debug cross platforms apps with PhoneGap
Page 4: Develop, test and debug cross platforms apps with PhoneGap
Page 5: Develop, test and debug cross platforms apps with PhoneGap

Development

Page 6: Develop, test and debug cross platforms apps with PhoneGap

DevelopmentPlatform

-Youcanrunitonalmostalltheplatforms

-TheonlyissueisthattobuildforiOSyouneedanOSX

device

-UsingonlinebuildservicesyoustillhavedependenciestoOSX

Page 7: Develop, test and debug cross platforms apps with PhoneGap
Page 8: Develop, test and debug cross platforms apps with PhoneGap

AvailableTools-SublimeText

-Vim-Eclipse

-IntelliJIDEA-AdobeBrackets

Page 9: Develop, test and debug cross platforms apps with PhoneGap

SublimeText-Youcansplittheeditorincolumnsandeditmultiplefiles

simultaneously-Distractionfreemode

-Superfastsearchengine-Superfaststartup

-Pluginsbased(cssprefixer,linter,etc.)

Page 10: Develop, test and debug cross platforms apps with PhoneGap

Vim-Fast

-Diffused-It'sacommandlinetool

Page 11: Develop, test and debug cross platforms apps with PhoneGap

Eclipse-VerywellintegratedwithAndroid(ADT)

-Multilanguage-Richofplugins

-Commandlineintegratedthroughplugins

Page 12: Develop, test and debug cross platforms apps with PhoneGap

IntelliJIDEA-Lowmemoryconsumption

-Multilanguage-Advancedcodecompletion

-Refactoringtools-HighlyintegratedwithAndroid(AndroidStudio)

Page 13: Develop, test and debug cross platforms apps with PhoneGap

AdobeBrackets-VeryintegratedwithPhoneGapservices

-Baseduponstandards-InlineCSSeditor

-Liveeditinginthebrowser

Page 14: Develop, test and debug cross platforms apps with PhoneGap

InstallPhoneGap-Downloadthedistributionyouaretargeting

(phonegap.comorgithub)-Unzipitandexplorethedirectories

Page 15: Develop, test and debug cross platforms apps with PhoneGap

RuntheLatestDistribution

Updatethe.cordova/config.jsonsoithasthisstructure:

{lib:{android:{id:'cordova-with-no-plugins',version:'3.0',uri:'/Users/giorgionatili/phonegap/src/cordova-android'

Page 16: Develop, test and debug cross platforms apps with PhoneGap

TheDirectories|-doc/...........sourcedocumentation|-lib/...........platformcodeforsupportedoperatingsystems||-android/||-blackberry/||-cordova-cli/||-ios/||-osx/||-windows-phone-7||-windows-phone-8||-windows8/|-changelog.....achangelogcompiledfromcommentsandauthors|-license.......theApacheSoftwareLicensev2

Page 17: Develop, test and debug cross platforms apps with PhoneGap

Node.js(+npm)-It'sawayofrunningJavaScriptoutsidethewebbrowser-It'sawrapperaroundthehigh-performanceV8JavaScript

runtime(Chrome)-Usefultocreatewebappsortoexecutecliutilitieswritten

inJavaScript-Downloadandinstallithttp://nodejs.org/

Page 18: Develop, test and debug cross platforms apps with PhoneGap

TheRequiredSDKs-Android:http://developer.android.com/sdk/index.html

-BlackBerry10:https://developer.blackberry.com/html5/downloads/

-FirefoxOS:http://goo.gl/Ugyst-iOS

https://developer.apple.com/devcenter/ios/index.action-WindowsPhonehttp://goo.gl/qjWro

AndroidSDK

Page 19: Develop, test and debug cross platforms apps with PhoneGap

AndroidSDK$exportPATH=$PATH:~/android-sdks/tools/

$exportPATH=$PATH:~/android-sdks/platform-tools/

(oredityour.bash_profilefile)Createavirtualdevice:

• Android4.0.3–APILevel15″(i.e.IceCreamSandwichMR1)• Assign2GiBtotheSDcard• Usetheskin“WXGA720″

• Setthevalue"Yes"fortheHardwareBack/Home

Page 20: Develop, test and debug cross platforms apps with PhoneGap

BlackBerrySDK-Addthetoolspathtoyourbash_profilefile

/Developer/SDKs/Research\In\Motion/BlackBerry\10\WebWorks\SDK\1.0.4.11/dependencies/tools/bin/

-GettheBlackBerry10applicationsigningkeysandgenerateadebugtoken

blackberry-signer-csksetup-cskpassCSJ_PASSblackberry-signer-register-csjpin15111974-cskpassCSJ_PASS~/Documents/blackberrykeys/client-RDK-2031902.csjblackberry-signer-register-csjpin15111974-cskpassCSJ_PASS~/Documents/blackberrykeys/client-PBDT-2031902.csj

Page 21: Develop, test and debug cross platforms apps with PhoneGap

iOSSDK-DownloadandinstallthelastversionofXcode

-Installios-sim(acommand-lineutilitythatlaunchestheappontheSimulator)

$curl-Lhttps://github.com/phonegap/ios-sim/zipball/1.3-oios-sim-1.3.zip

$unzipios-sim-1.3.zip

$rakeinstallprefix=/usr/local/

Page 22: Develop, test and debug cross platforms apps with PhoneGap

WindowsPhone-DownloadandinstallVisualStudio

-DownloadandinstallCygwinhttp://www.cygwin.com

Page 23: Develop, test and debug cross platforms apps with PhoneGap
Page 24: Develop, test and debug cross platforms apps with PhoneGap

Chrome-DevTools

-RemoteDebugging-Experimentalflags

Page 25: Develop, test and debug cross platforms apps with PhoneGap

InternetExplorer-DevTools

-Workersdebugging

Page 26: Develop, test and debug cross platforms apps with PhoneGap

Firefox-3DView

-Scratchpad

Page 27: Develop, test and debug cross platforms apps with PhoneGap

Safari-RemoteDebugging

Page 28: Develop, test and debug cross platforms apps with PhoneGap

MakeYourShellSexy

-InstalliTerm(Splitpaneview,searchhighlight,mouse-lesscopy)

-Installzsh(sharedcommandhistory,fullofplugins,dotfiles)

-Pickupanicethemehere

Page 29: Develop, test and debug cross platforms apps with PhoneGap

DownloadthetargetSDK,installnode.js,npmandcheckthatnodeisworking.

Downloadandinstalladevenvironment.

Page 30: Develop, test and debug cross platforms apps with PhoneGap
Page 31: Develop, test and debug cross platforms apps with PhoneGap

Installcordova-cli$npmintallcordova-g

$sudochown-Rgiorgionatili/usr/local/lib/node_modules/cordova

Page 32: Develop, test and debug cross platforms apps with PhoneGap

CreateaProject$cordovacreateMySampleProject

Page 33: Develop, test and debug cross platforms apps with PhoneGap

AddaPlatform+Run!

$cordovaplatformsaddandroid

$cordovaemulateandroid

Page 34: Develop, test and debug cross platforms apps with PhoneGap

Checkitrunning

Page 35: Develop, test and debug cross platforms apps with PhoneGap

Theindex.htmlfile<html><head><metacharset="utf-8"/><metaname="format-detection"content="telephone=no"/><metaname="viewport"content="user-scalable=no,initial-scale=1,maximum-scale=1,minimum-scale=1,width=device-width,height=device-height,target-densitydpi=device-dpi"/><linkrel="stylesheet"type="text/css"href="css/index.css"/><title>HelloWorld</title></head><body>

Page 36: Develop, test and debug cross platforms apps with PhoneGap

Theindex.jsfilevarapp={//ApplicationConstructorinitialize:function(){this.bindEvents();},//BindEventListeners////Bindanyeventsthatarerequiredonstartup.Commoneventsare://'load','deviceready','offline',and'online'.bindEvents:function(){document.addEventListener('deviceready',this.onDeviceReady,false);},

Page 37: Develop, test and debug cross platforms apps with PhoneGap

Usingcordova-clicreateanewPhoneGapprojectandrunitonatestdeviceoremulator.

Page 38: Develop, test and debug cross platforms apps with PhoneGap
Page 39: Develop, test and debug cross platforms apps with PhoneGap

CloudsBuildServices

-Lesspainconfiguringallthetargetplatforms-GitHubintegration-Easyinstallprocess

BuildUsing

Page 40: Develop, test and debug cross platforms apps with PhoneGap

BuildUsingcordova-cli

$createpath[id[name]]

$cordovaplatformadd[platform]|rm|ls

$cordovaprepare[platform]

$cordovacompile[platforms]

$cordovabuild

$cordovaemulate[platforms]

Page 41: Develop, test and debug cross platforms apps with PhoneGap

$cordovaemulate[platforms]

TheProjectFoldersmyApp/|--.cordova/|--merges/||--android/||--blackberry/|`--ios/|--platforms/||--android/||--blackberry/|`--ios/|--plugins/`--www/

Page 42: Develop, test and debug cross platforms apps with PhoneGap

Theconfig.xmlfile(adetailedexplanationoftheallowedtagsisavailable

herehttp://goo.gl/GqXY0)<widgetxmlns="http://www.w3.org/ns/widgets"xmlns:gap="http://phonegap.com/ns/1.0"id="com.phonegap.hello-world"version="1.0.0">

<name>HelloWorld</name>

<description>HelloWorldsampleapplicationthatrespondstothedevicereadyevent.

Page 43: Develop, test and debug cross platforms apps with PhoneGap
Page 44: Develop, test and debug cross platforms apps with PhoneGap

TheBrowser-Findtherelevantcodeinthedebugger’scodeviewpane-Setbreakpoint(s)whereyouthinkinterestingthingsmay

occur-Runthescriptagainbyreloadingthepageinthebrowser

-Investigatethevaluesofvariables

Page 45: Develop, test and debug cross platforms apps with PhoneGap

iWebInspector(OSXonly)

-Atooltodebug,profileandinspectwebapplicationsrunningoniOSSimulator-ItworksoniOS5andiOS5.1-Findtheapplication:didFinishLaunchingWithOptionsmethodintheAppDelegate.mfileandaddthefollowingsnippet iOS6Remote

Page 46: Develop, test and debug cross platforms apps with PhoneGap

iOS6RemoteDebugging

-YoumusthavetheSafariDevelopMenuenabled

-OpenDevelop->(iPad||iPhone)SimulatorandclicktheDebugwithweinre

Page 47: Develop, test and debug cross platforms apps with PhoneGap

-OpenDevelop->(iPad||iPhone)Simulatorandclicktheactivesession

Debugwithweinre(WEbINspector

REmote)-Installweinreusingthecommandlinetool

$npminstallweinre-g

-Addthescripttagneededtoloadtherequiredlibraries<scriptsrc="http://xxx.xxx.xxx.xxx:8080/target/target-script.js#anonymous"></script>

-Runitfromyourcommandlineandopenabrowser

Page 48: Develop, test and debug cross platforms apps with PhoneGap

weinre-boundHostxxx.xx.xx.x

Configureyourappinordertorunaremotedebugsessionusingweinre

Page 49: Develop, test and debug cross platforms apps with PhoneGap
Page 50: Develop, test and debug cross platforms apps with PhoneGap

Ripple-ApacheRipple™isawebbasedmobileenvironment

simulatordesignedtoenablerapiddevelopmentofmobilewebapplications

-ItworksviaaChromeextension,whichmeans,obviously,itisChromeonly

-ItsupportsmostoftheplatformssupportedbyPhoneGap$cordovaripple[platform]

TheRippleUI

Page 51: Develop, test and debug cross platforms apps with PhoneGap

TheRippleUI

Page 52: Develop, test and debug cross platforms apps with PhoneGap

ResponsiveInspector

-AllowsviewingdefinedmediaqueriesofHTMLpages-Usefulwhendevelopingresponsiveweblayouts

-AvailableasaChromeextension

Page 53: Develop, test and debug cross platforms apps with PhoneGap

ResponsiveInspectorUI

Page 54: Develop, test and debug cross platforms apps with PhoneGap

LiveReload-It'sautilitythatrefreshesthepageforyoueachtimeit

detectsachangetoafileinadirectory-Youcanactivateitusinganextension

http://goo.gl/kZaClorbyaddingthefollowingscripttothepage

<script>document.write('<scriptsrc="http://'+(location.host||'localhost').split(':')[0]+':35729/livereload.js?snipver=1"></'+'script>')</script>

EmulatorvsDevice

Page 55: Develop, test and debug cross platforms apps with PhoneGap

EmulatorvsDevice-Emulatorsallowyoutomakeafirstcheckandfixthemost

obviousbugs-Emulatorsoffera(relatively)easywaytorunappson

multipleplatforms-Devicesallowtorunrealtests

-Devicesfragmentationdon'tallowyoutoruntestsonallthedevices

-Bugsenseandcrowdtestingcanhelpdeveloperstodeployreliableapps

Page 56: Develop, test and debug cross platforms apps with PhoneGap

CordovaCLI-Youcanrunthemaincommandsfromanyfolder-Whenworkingonaspecifictargetplatformrunthe

commandscontainedinthecordovafolder-Keepdevicesconnectedtoyourdevenvironmentinorder

totestoften

Page 57: Develop, test and debug cross platforms apps with PhoneGap

PhoneGap

Page 58: Develop, test and debug cross platforms apps with PhoneGap

PhoneGapArchitecture

PhoneGapEvent

Page 59: Develop, test and debug cross platforms apps with PhoneGap

PhoneGapEventFlow

Page 60: Develop, test and debug cross platforms apps with PhoneGap

PerformanceTips-Avoidembedandinlinescripts-Minimizerepaintsandreflows

-MinimizeHTMLfiles-CompressandcombineJavaScriptandCSSfiles

-UseCSSsprites

Page 61: Develop, test and debug cross platforms apps with PhoneGap

CompressionsTools-Thereareseveralcompressiontools(YUICompressor,

JSMin,Closure,KJScompress,bananascript)-UglifyJS2startedtobeprettyfamoussincejQuerystarted

touseit-Verysimpletoinstallandtouse

$npminstalluglify-js-g

$catfile1.jsfile2.js|uglifyjs--inline-script-omytest.min.js

Page 62: Develop, test and debug cross platforms apps with PhoneGap

ClientSideTemplating

Adocumentthatcontainsparameters,identifiedbysomespecialsyntax,thatarereplacedbyactualargumentsbythetemplate

processingsystem

-Itisagreatwaytoseparatemarkupandlogicinviews-It'sduetoshiftoftheapplogicfromservertoclient

Page 63: Develop, test and debug cross platforms apps with PhoneGap

TemplatingEngines-underscore.js,templatesarefastandlightweight

-ICanHaz.js,returnsjQueryobject-GoogleClosureTemplates,robustandreliable

-Mustache.js,nologicinthetemplatesthatarelanguageagnostic

-Evenmore...

Page 64: Develop, test and debug cross platforms apps with PhoneGap

TemplateandDataAtemplateanditsdatalooklikethefollowingsnippets:

<h1>{{title}}</h1><ul>{{#names}}<li>{{name}}</li>{{/names}}</ul>

vardata={"title":"Story","names":[{"name":"Tarzan"},

Page 65: Develop, test and debug cross platforms apps with PhoneGap

UsingTemplates-Atemplatecanbeloadedonruntimeorcompiledand

storedinavariable-Ausefultooltocompilethetemplateasavariableis

pistachio$npminstallpistachio-g

$pistachio--out=splash-tpl.jssplash-tpl.htmlJavaScriptAMD

Page 66: Develop, test and debug cross platforms apps with PhoneGap

JavaScriptAMDSpecifiesamechanismfordefiningmodulessuchthatthemoduleand

itsdependenciescanbeasynchronouslyloaded

-Wellsuitedforthebrowserwheresynchronousloadingincursperformance,usability,debugging,andcross-domainaccess

problems

• Dojo:dojo.require('some.module')

• LABjs:$LAB.script("some/module.js')

• CommonJS:require('some/module').

Page 67: Develop, test and debug cross platforms apps with PhoneGap

Require.js-JavaScriptfileandmoduleloader-Optimizedforin-browseruse,butitcanbeusedinotherJSenvironments

<scriptdata-main="js/app"src="js/libs/require/require.js"></script>

www/|--js/||--app.js||--main.js||--libs/

Page 68: Develop, test and debug cross platforms apps with PhoneGap

AnatomyofaModule1/2

-EachmoduleisdefinedinaseparateJavaScriptfile-Amoduleisdefinedusingthedefinekeywordandreturnsomething

define({color:"black",size:"unisize"

Page 69: Develop, test and debug cross platforms apps with PhoneGap

AnatomyofaModule2/2

-Somedefine()callsthatincludeanameforthemoduleasthefirstargument-Ifthemodulehasdependencies,thefirstargumentshouldbeanarrayofdependencynames,andthesecondargumentshouldbeadefinitionfunction

Page 70: Develop, test and debug cross platforms apps with PhoneGap

Usingtherequire.jssyntaxcreateanewPhoneGap

applicationthatreactstothedevicereadyevent.

Page 71: Develop, test and debug cross platforms apps with PhoneGap
Page 72: Develop, test and debug cross platforms apps with PhoneGap

LocalStorage-TheLocalStorageAPIispartoftheWebStorageAPIdefinedbytheW3Cinordertoprovideaguidelineforpersistentdatastorageofkey-

valuepairdatainwebclients

-LocalStorageAPIisdesignedtosupportdatathatneedstobeavailablebetweensessions

Page 73: Develop, test and debug cross platforms apps with PhoneGap

ThelocalStorageObject

Itexposesseveralpropertiesandmethods:

• key:returnsthenameofthekeystoredataspecificposition• getItem:returnstheitemidentifiedbyakey• setItem:savessomedatainaspecifickey(i.e.astring)ofthelocalStorageobject

Page 74: Develop, test and debug cross platforms apps with PhoneGap

TheStorageEventObject

EachtimethelocalStorageobjectisupdatedaStorageEventisfired.Thiseventcannotbecancelledandcontainsthefollowingproperties:

• key:astringthatrepresentsthenamedkeythatwasadded,removed,ormodified• oldValue:thepreviousvalueofthenamedkeyifitwasupdatedornull

Page 75: Develop, test and debug cross platforms apps with PhoneGap

LocalStorageDrawbacks

-TheAPIissynchronousandforthisreasontheappappearslessresponsivebecausethetimeneededtoaccessthelocalStorageobjectisgreaterthantheoneneededtoaccessanobjectinmemory

-Complexdataneedstobeserializedandde-serializedimpactingtheresponsivenessoftheapp

Page 76: Develop, test and debug cross platforms apps with PhoneGap

Createasampleappabletostoreinthelocalstoragepreviouslytypedwordssothattheendusercaneasily

getsomesuggestionsthenexttimeisusingtheapp

Page 77: Develop, test and debug cross platforms apps with PhoneGap

SQLStorage-PhoneGapprovidesSQLstorageAPIbasedontheWebSQL

specification-WhenadevicealreadyofferssupportforWebSQLtheapp

willuseitotherwisetheappwillusethePhoneGapone-Asadeveloperyouwillnotnoticeanydifference,because

youwillnothavetochangeanylineofcode

Page 78: Develop, test and debug cross platforms apps with PhoneGap

CreatetheAppDatabase

InordertostarttoworkwithaDatabaseobjectit’senoughtostoreinavariablewhat’sreturnedbytheopenDatabasemethod

varsize=(1024*1024*2);vardb=window.openDatabase("test","1.0","TestDB",size);

TheopenDatabasemethodacceptsfourarguments;thenameofthe

Page 79: Develop, test and debug cross platforms apps with PhoneGap

TheDataBaseObject

TheDataBaseobjectreturnedbytheopenDatabasemethodexposestwomethods:

• transaction->executeanSQLtransaction• changeVersion->changestheversionofthedb(usefulwhenupdatingaschema)

Page 80: Develop, test and debug cross platforms apps with PhoneGap

TheSQLTransactionObject

Theobjectisreturnedasanargumentinthefunctiondefinedasfirstargumentofthetransactionmethod

TheexecuteSqlmethodallowsexecutingSQLqueries:

functioncreateTables(transactionObj){

Page 81: Develop, test and debug cross platforms apps with PhoneGap

ArgumentsandtheQuery

Youcanuseplaceholderstopassargumentstoaquerywhenusingthetransactionmethod

functionaddData(name,surname,gender){

db.transaction(function(transactionObj){

varsql='INSERTINTOusers(name,surname,gender)VALUES(?,?,?);';

Page 82: Develop, test and debug cross platforms apps with PhoneGap

TheSQLResultSetObject

WhenaSQLTransactionobject'sexecuteSqlmethodiscalled,thespecifiedcallbackexecuteswithaSQLResultSetparametercontainingthreeproperties:

• TheinsertIdreturnstherownumberofasuccessfullySQLinsertionstatement

Page 83: Develop, test and debug cross platforms apps with PhoneGap

TheSQLResultSetRowListTheSQLResultSetRowListcontainsthedatareturnedfromaSQLselectstatement,theobjectexposes:

functionquerySuccess(tx,results){varlen=results.rows.length;for(vari=0;i<len;i++){

• Thelengthpropertyindicatinghowmanyrowstheselectstatementreturns• Theitemmethodtorecoverdataataspecificindex

Page 84: Develop, test and debug cross platforms apps with PhoneGap

DataBaseLimitations

LimitationsarenotrelatedtoPhoneGapitselfbutareduetotheWebViewimplementationofeachtargetplatform

• ThesizelimitvariesaccordinglytotheOSfrom5to25Mb• SinceiOS5.xdatabaseshavebeenmovedtothefolder~/Library/Cachesfrom~/Library/WebKit

Page 85: Develop, test and debug cross platforms apps with PhoneGap

Createasampleappabletostoreandreadsomedatafromalocaldatabase

Page 86: Develop, test and debug cross platforms apps with PhoneGap
Page 87: Develop, test and debug cross platforms apps with PhoneGap

AccelerometerTheaccelerometerisactuallymadeupofthreeaccelerometersandeachonemeasuresthechangesinvelocity(i.e.,linearacceleration)overtimealongthelinearpathontheaxisx,y,andz

Page 88: Develop, test and debug cross platforms apps with PhoneGap

AccelerometerObject

Theaccelerometerdetectsthevaluesofthedeltamovementrelativetothecurrentdeviceposition

YoucandetectthedeviceaccelerationdatausingthemethodgetCurrentAccelerationorsettingupawatcherthroughthemethodwatchAcceleration

Inordertostopwatchingtheaccelerometerdatait’senoughtocall

Page 89: Develop, test and debug cross platforms apps with PhoneGap

AccelerometerDatavaroptions={maximumAge:3000,timeout:5000,enableHighAccuracy:true};navigator.geolocation.watchPosition(onScucces,onFailure,options);

functiononSuccess(position){

console.log('Coordinates:'+position.coords);console.log('Altitude:'+position.coords.altitude);console.log('Altitude:'+position.coords.altitude);console.log('Accuracy:'+position.coords.accuracy);console.log('AltitudeAccuracy:'+position.coords.altitudeAccuracy);console.log('Heading:'+position.coords.heading);console.log('Speed:'+position.coords.speed);

Page 90: Develop, test and debug cross platforms apps with PhoneGap

Createasampleapptodetectdeviceshakesusinganumericvalueasboundbetweenthepreviousandactual

positionofthedevice

Page 91: Develop, test and debug cross platforms apps with PhoneGap

CompassThePhoneGapCompassAPIallowsyoutoobtainthedirectionthatthedeviceispointingto

TheCompassAPIisavailableonthecompasspropertyofthenavigatorobjectandexposesthefollowingmethods:

• compass.getCurrentHeading,readsthecurrentcompassheadingthroughahandler• compass.watchHeading,readsthecompassheadingataspecifictimeintervalthroughanhandlerandreturnareferencetoit

Page 92: Develop, test and debug cross platforms apps with PhoneGap

CompassHeadingObject

It'sreturnedasanargumentinthesuccesshandlerofthewatchHeadingandgetCurrentHeadingmethods,theobjectexposesthefollowingproperties:

• magneticHeading,theheadingindegreesfrom0to359.99• trueHeading,theheadingrelativetothegeographicNorthPole

Page 93: Develop, test and debug cross platforms apps with PhoneGap

CompassErrorObject

TheCompassErrorobjecthasapropertynamedcodethatreturnstwopossiblevaluesCompassError.COMPASS_INTERNAL_ERRorCompassError.COMPASS_NOT_SUPPORTED

functiononCompassError(error){

switch(true){

Page 94: Develop, test and debug cross platforms apps with PhoneGap

Considerthefollowingsnippetofcode,whichwillgiveyoutherightrotationforthecompass,andcreateasampleappshowinga

Page 95: Develop, test and debug cross platforms apps with PhoneGap
Page 96: Develop, test and debug cross platforms apps with PhoneGap

GeolocationThetermgeolocationisusedinordertorefertotheidentificationprocessofthereal-worldgeographiclocationofanobject

Thelocationofadeviceisrepresentedthroughapoint,thepointiscomprisedoftwocomponents:latitudeandlongitude

Page 97: Develop, test and debug cross platforms apps with PhoneGap

GeolocationAPITheGeolocationAPIisexposedthroughthegeolocationobjectchildofthenavigatorobjectandconsistsofthreemethods:

• getCurrentPosition(),returnsthedeviceposition• watchPosition(),watchesforchangesofthedeviceposition• clearWatch(),stopsthewatcherfordevice’spositionchanges

Page 98: Develop, test and debug cross platforms apps with PhoneGap

PositionObjectAccessingitspropertiesyoucanreadthedevice’scoordinatesandthecreationtimestampoftheobjectthatstoresthecoordinates

functiononSuccess(position){

console.log('Coordinates:'+position.coords);console.log('Timestamp:'+position.timestamp);

}

Page 99: Develop, test and debug cross platforms apps with PhoneGap

PositionErrorObjectItcontainstwopropertiesthecodeandthemessageone.

functiononError(error){switch(true){caseerror.code==PositionError.PERMISSION_DENIED://Theuserdeniestheapptousethedevice’scurrentpositionbreak;

caseerror.code==PositionError.POSITION_UNAVAILABLE://Thepositionofthedevicecannotbedeterminedbreak;

Page 100: Develop, test and debug cross platforms apps with PhoneGap
Page 101: Develop, test and debug cross platforms apps with PhoneGap

Camera&CaptureThemaindifferencebetweentheseAPIsisthattheCameraAPIcanaccessonlythedefaultdevicecameraapplicationwhereastheCaptureAPIcanalsorecordaudioorvideo

CaptureAPIallowsmultiplecaptureswithasingleAPIcall

TheCaptureAPIisanimplementationofanabandonedW3Cstandardsdraft

Page 102: Develop, test and debug cross platforms apps with PhoneGap

AccessingtheCameraTheCameraAPIexposestwomethodsdefinedinthenavigator.cameraobject:

• getPicture,whichopensthedefaultcameraapplicationorletstheuserbrowsethemedialibrarydependingontheoptionsspecifiedintheconfigurationobjectthemethodacceptsasargument• cleanup,whichcleansuptheimagefilestoredintothetemporarystoragelocation

Page 103: Develop, test and debug cross platforms apps with PhoneGap

CameraOptions• quality,anumberbetween0and100usedtospecifythequalityofthesavedimage• destinationType,anumberusedtodefinetheformatofthevaluereturnedinthesuccesshandler(Camera.DestinationType.DATA_URL,Camera.DestinationType.FILE_URI,Camera.DestinationType.NATIVE_URI)• sourceType,anumberusedtospecifywherethegetPicturemethodwillgetanimage(Camera.PictureSourceType.PHOTOLIBRARY,Camera.PictureSourceType.CAMERA,

Page 104: Develop, test and debug cross platforms apps with PhoneGap

CapturinganImagevarcameraOptions={targetWidth:300,targetHeight:400,saveToPhotoAlbum:true,allowEdit:true};

navigator.camera.getPicture(onCameraSuccess,onCameraError,cameraOptions);functiononCameraSuccess(imageData){

//Usetheimagedata

}

functiononCameraError(error){

Page 105: Develop, test and debug cross platforms apps with PhoneGap

CaptureAPITheCaptureAPIworksasynchronouslyasmostofthePhoneGapAPIsandprovidesaccesstotheaudio,image,andvideocapturecapabilitiesofthedevice

varcapture=navigator.device.capture;capture.captureImage(function(files){

• captureVideo• captureAudio• captureImage

Page 106: Develop, test and debug cross platforms apps with PhoneGap

MediaFileObjectTheMediaFileobjectstoredinthefilesarrayreturnedinthesuccesshandlerdescribesthecapturedmedia

• fullPath,astringrepresentingthefilepathonthedeviceincludingthefilename• lastModifiedDate,modificationdateofthefileexpressedinmssinceJanuary1,1970• name,astringrepresentingthenameofthefile• size,anumberrepresentingthesizeofthefileinbytes

Page 107: Develop, test and debug cross platforms apps with PhoneGap

CaptureOptions• CaptureVideoOptions(limitandduration)• CaptureImageOptions(limit)• CaptureAudioOptions(limitandduration)

Page 108: Develop, test and debug cross platforms apps with PhoneGap

CaptureErrorObject• CaptureError.CAPTURE_INTERNAL_ERR• CaptureError.CAPTURE_APPLICATION_BUSY• CaptureError.CAPTURE_INVALID_ARGUMENT• CaptureError.CAPTURE_NO_MEDIA_FILES• CaptureError.CAPTURE_NOT_SUPPORTED

Page 109: Develop, test and debug cross platforms apps with PhoneGap

Createasampleappabletocaptureanimageandapplythegrayscaleeffectyoucanfindhere

http://www.html5rocks.com/en/tutorials/canvas/imagefilters/.

Page 110: Develop, test and debug cross platforms apps with PhoneGap
Page 111: Develop, test and debug cross platforms apps with PhoneGap

UnderstandingtheAPI

ThePhoneGapFilesAPIisanimplementationoftwodifferentW3CAPIs,theDirectoriesandSystemAPIandtheFileAPI

ThePhoneGapFilesAPIisnotacompleteimplementationoftheW3Cspecification,themissingpieceisthesynchronousfilesysteminterfaceimplementation

Page 112: Develop, test and debug cross platforms apps with PhoneGap

AccessingtheFileSystem

InordertoaccessthedevicefilesystemyoucanusetherequestFileSystemmethodoftheLocalFileSystemobject

Themethodacceptsfourarguments:

• Thetypeofstorage(temporaryorpersistent)• Theamountofspaceinbytestobeallocatedonthedevice

Page 113: Develop, test and debug cross platforms apps with PhoneGap

StorageTypes

Thedeviceharddiskisnotcompletelyopentotheapp’sview.Alimitedportionoftheharddiskisdedicatedtoasingleappalone;thisistheappsandbox.

• LocalFileSystem.PERSISTENTindicatesthatthestoragecannotberemovedbytheuseragentwithouttheapp’soruser’spermission• LocalFileSystem.TEMPORARYindicatesthatthefilesstoredintherequestedspacecanbedeletedbytheuseragentorbythesystemwithouttheapp’soruser’spermission

Page 114: Develop, test and debug cross platforms apps with PhoneGap

ReadingDirectories&Files

functiononSuccess(fileSystem){

varcurrentRoot=fileSystem.root;

vardirectoryReader=currentRoot.createReader();directoryReader.readEntries(onDirSuccess,onFileSysError);

}

Page 115: Develop, test and debug cross platforms apps with PhoneGap

FileErrorObject• FileError.NOT_FOUND_ERR(returnedvalue1)• FileError.SECURITY_ERR(returnedvalue2)• FileError.ABORT_ERR(returnedvalue3)• FileError.NOT_READABLE_ERR(returnedvalue4)• FileError.ENCODING_ERR(returnedvalue5)• FileError.NO_MODIFICATION_ALLOWED_ERR(returnedvalue6)• FileError.INVALID_STATE_ERR(returnedvalue7)

Page 116: Develop, test and debug cross platforms apps with PhoneGap

WritingDataTowritedatatoafileitsufficesthattheappgetsaccesstothefileusingtheFileWriterobject

TogetaFileWriterobjectyoufirsthavetogetaccesstoaDirectoryEntryortoaFileEntryobjectusingtherequestFileSystemmethod

Onceyousuccessfullygetaccesstothefilesystemyoucanrequestafilespecifyingthatyouwanttocreateitusingthecreateflag

functiononFileSystemSuccess(fileSystem){

Page 117: Develop, test and debug cross platforms apps with PhoneGap

CreatingaWriterInthesuccesshandlerit'spossibletocreateawriter,thecreateWritermethodalsorequiresthesuccessandfailurehandlers

functiononGetFile(file){

file.createWriter(onGetWriter,onGetWriterError);

}

functiononGetWriter(writer){

writer.write('HelloPhoneGapFilesAPI!');

Page 118: Develop, test and debug cross platforms apps with PhoneGap

EventsDuringthewriteoperationseveraleventsoccur;foreacheventthereisacorrespondingpropertydefinedontheFileWriterobject:

• onwritestartiscalledwhentheFileWriterobjectstartstowritethefile• onwriteiscalledwhentheFileWriterobjecthascompletedsuccessfullythewriteoperation• onabortiscalledwhenthewriteoperationhasbeeninterrupted

Page 119: Develop, test and debug cross platforms apps with PhoneGap

ReadingDataOnceyouhaveaccesstothefileyoucancreateaFileReaderobjectanduseitsmethods:

• readAsDataURL,readsfileandreturndataasabase64-encodeddataURL• readAsText,readstextfile• readAsBinaryString,readsfileasbinaryandreturnsabinarystring• readAsArrayBuffer,readsfileasanArrayBuffer

Page 120: Develop, test and debug cross platforms apps with PhoneGap

DownloadandUpload

OnceyougetaccesstothefilesystemcreateanewFileTransferobjectandcallthedownloadmethodspecifyingtheremoteURL,thesystemfilepathURI,andthesuccessfailurehandlers

varft=newFileTransfer();ft.upload(fileURI,encodeURI("http://some.server.com/upload.php"),onSuccess,onError,options);

Page 121: Develop, test and debug cross platforms apps with PhoneGap

FileUploadOptions• fileKey:thenameoftheformelement.Defaultstofile• fileName:thefilenametousewhensavingthefileontheserver.• mimeType:themimetypeofthedatatoupload• params:asetofoptionalkey/valuepairstopassintheHTTPrequest• chunkedMode:whethertouploadthedatainchunkedstreamingmode

Page 122: Develop, test and debug cross platforms apps with PhoneGap

Createasampleappandrenderaprogressbarindicatingtheamountoffiledownloadedfromaremoteserver

Page 123: Develop, test and debug cross platforms apps with PhoneGap
Page 124: Develop, test and debug cross platforms apps with PhoneGap

ContactNameObject

• formatted,representsthecompletenameofthecontact• familyName,representsthecontact’sfamilyname• givenName,representsthecontact’sgivenname• middleName,representsthecontact’smiddlename• honorificPrefix,representsthecontact’sprefix(e.g.,Mr.orDr.)

Page 125: Develop, test and debug cross platforms apps with PhoneGap

ContactFieldObject• type,astringthatrepresentsthetypeoffield,possiblevaluesarehome,work,mobile,andsoon• value,astringrepresentingthevalueofthefieldsuchasaphonenumberoremailaddress• pref,aBooleanvaluethatindicatesifinaspecificfieldisreturnedtheuserpreferredvalue

Page 126: Develop, test and debug cross platforms apps with PhoneGap

ContactAddressObject

• pref,aBooleanthatindicateswhetherthereturnedContactAddressisthepreferredvalueoftheuserfortheContactAddressobject• type,astringthatindicateswhattypeofaddressisstoredintheContactAdressobject(e.g.,home,office,etc.)• formatted,astringthatrepresentsthecompleteaddress

Page 127: Develop, test and debug cross platforms apps with PhoneGap

ReadaContactObject

Createacontact:varcontact=navigator.contacts.create({'displayName':'Giorgio'});

contact.save(onContactSaved,onContactSavedError);contact.remove(onContactRemoved,onContactRemovedError);

Findacontact:varoptions=newContactFindOptions();

Page 128: Develop, test and debug cross platforms apps with PhoneGap
Page 129: Develop, test and debug cross platforms apps with PhoneGap

WhatisaPluginIt'sanativecodeexposedtotheappusingJavaScript

Thenativepartextendsorimplementsplatformspecificclassesorinterfaces(e.g.CordovaPlugin,CDVPlugin,etc.)

Aplugincanbeinstalledanduninstalledusingcordova-cliorplugmansadas

Page 130: Develop, test and debug cross platforms apps with PhoneGap

PhoneGapArchitecture

Page 131: Develop, test and debug cross platforms apps with PhoneGap

PlugmanPlugmanisanopensourcecommandlineutilitydistributedasannpmmoduletofacilitatetheinstallationanduninstallationofplugins

ItsupportstheAndroid,BlackBerry10andiOSplatforms

Onceinstalledyoucanuseseveralcommandsfromyourcommandlinetool

Page 132: Develop, test and debug cross platforms apps with PhoneGap

PlugmanCommands

$plugman--fetch

$plugman--platformandroid--projectPLATFORM_PROJECT_PATH--plugin

$plugman--prepare

$plugman--platformandroiduninstall--projectPLATFORM_PROJECT_PATH--plugin

Page 133: Develop, test and debug cross platforms apps with PhoneGap

BuildingBlocksofaPlugin

APhoneGappluginisabridgebetweentheWebViewandthenativeplatformtheappisrunningon

TheonlymandatoryimplementationisthewaytocommunicatebetweenJavaScriptandthenativeenvironmentusingthecordova.execfunction

Page 134: Develop, test and debug cross platforms apps with PhoneGap
Page 135: Develop, test and debug cross platforms apps with PhoneGap

Links• Officialdocumentationhttp://docs.phonegap.com• GoogleGrouphttps://groups.google.com/forum/#!forum/phonegap• AndrewTriceblobhttp://www.tricedesigns.com/tag/phonegap• SimonMcDonaldbloghttp://simonmacdonald.blogspot.com/search/label/phonegap• JoeBowserbloghttp://www.infil00p.org• RaymondCamdenbloghttp://www.raymondcamden.com/index.cfm/Mobile

Page 136: Develop, test and debug cross platforms apps with PhoneGap

Book(s)

Page 137: Develop, test and debug cross platforms apps with PhoneGap