develop, test and debug cross platforms apps with phonegap
Post on 13-Aug-2015
48 Views
Preview:
TRANSCRIPT
Development
DevelopmentPlatform
-Youcanrunitonalmostalltheplatforms
-TheonlyissueisthattobuildforiOSyouneedanOSX
device
-UsingonlinebuildservicesyoustillhavedependenciestoOSX
AvailableTools-SublimeText
-Vim-Eclipse
-IntelliJIDEA-AdobeBrackets
SublimeText-Youcansplittheeditorincolumnsandeditmultiplefiles
simultaneously-Distractionfreemode
-Superfastsearchengine-Superfaststartup
-Pluginsbased(cssprefixer,linter,etc.)
Vim-Fast
-Diffused-It'sacommandlinetool
Eclipse-VerywellintegratedwithAndroid(ADT)
-Multilanguage-Richofplugins
-Commandlineintegratedthroughplugins
IntelliJIDEA-Lowmemoryconsumption
-Multilanguage-Advancedcodecompletion
-Refactoringtools-HighlyintegratedwithAndroid(AndroidStudio)
AdobeBrackets-VeryintegratedwithPhoneGapservices
-Baseduponstandards-InlineCSSeditor
-Liveeditinginthebrowser
InstallPhoneGap-Downloadthedistributionyouaretargeting
(phonegap.comorgithub)-Unzipitandexplorethedirectories
RuntheLatestDistribution
Updatethe.cordova/config.jsonsoithasthisstructure:
{lib:{android:{id:'cordova-with-no-plugins',version:'3.0',uri:'/Users/giorgionatili/phonegap/src/cordova-android'
TheDirectories|-doc/...........sourcedocumentation|-lib/...........platformcodeforsupportedoperatingsystems||-android/||-blackberry/||-cordova-cli/||-ios/||-osx/||-windows-phone-7||-windows-phone-8||-windows8/|-changelog.....achangelogcompiledfromcommentsandauthors|-license.......theApacheSoftwareLicensev2
Node.js(+npm)-It'sawayofrunningJavaScriptoutsidethewebbrowser-It'sawrapperaroundthehigh-performanceV8JavaScript
runtime(Chrome)-Usefultocreatewebappsortoexecutecliutilitieswritten
inJavaScript-Downloadandinstallithttp://nodejs.org/
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
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
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
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/
WindowsPhone-DownloadandinstallVisualStudio
-DownloadandinstallCygwinhttp://www.cygwin.com
Chrome-DevTools
-RemoteDebugging-Experimentalflags
InternetExplorer-DevTools
-Workersdebugging
Firefox-3DView
-Scratchpad
Safari-RemoteDebugging
MakeYourShellSexy
-InstalliTerm(Splitpaneview,searchhighlight,mouse-lesscopy)
-Installzsh(sharedcommandhistory,fullofplugins,dotfiles)
-Pickupanicethemehere
DownloadthetargetSDK,installnode.js,npmandcheckthatnodeisworking.
Downloadandinstalladevenvironment.
Installcordova-cli$npmintallcordova-g
$sudochown-Rgiorgionatili/usr/local/lib/node_modules/cordova
CreateaProject$cordovacreateMySampleProject
AddaPlatform+Run!
$cordovaplatformsaddandroid
$cordovaemulateandroid
Checkitrunning
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>
Theindex.jsfilevarapp={//ApplicationConstructorinitialize:function(){this.bindEvents();},//BindEventListeners////Bindanyeventsthatarerequiredonstartup.Commoneventsare://'load','deviceready','offline',and'online'.bindEvents:function(){document.addEventListener('deviceready',this.onDeviceReady,false);},
Usingcordova-clicreateanewPhoneGapprojectandrunitonatestdeviceoremulator.
CloudsBuildServices
-Lesspainconfiguringallthetargetplatforms-GitHubintegration-Easyinstallprocess
BuildUsing
BuildUsingcordova-cli
$createpath[id[name]]
$cordovaplatformadd[platform]|rm|ls
$cordovaprepare[platform]
$cordovacompile[platforms]
$cordovabuild
$cordovaemulate[platforms]
$cordovaemulate[platforms]
TheProjectFoldersmyApp/|--.cordova/|--merges/||--android/||--blackberry/|`--ios/|--platforms/||--android/||--blackberry/|`--ios/|--plugins/`--www/
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.
TheBrowser-Findtherelevantcodeinthedebugger’scodeviewpane-Setbreakpoint(s)whereyouthinkinterestingthingsmay
occur-Runthescriptagainbyreloadingthepageinthebrowser
-Investigatethevaluesofvariables
iWebInspector(OSXonly)
-Atooltodebug,profileandinspectwebapplicationsrunningoniOSSimulator-ItworksoniOS5andiOS5.1-Findtheapplication:didFinishLaunchingWithOptionsmethodintheAppDelegate.mfileandaddthefollowingsnippet iOS6Remote
iOS6RemoteDebugging
-YoumusthavetheSafariDevelopMenuenabled
-OpenDevelop->(iPad||iPhone)SimulatorandclicktheDebugwithweinre
-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
weinre-boundHostxxx.xx.xx.x
Configureyourappinordertorunaremotedebugsessionusingweinre
Ripple-ApacheRipple™isawebbasedmobileenvironment
simulatordesignedtoenablerapiddevelopmentofmobilewebapplications
-ItworksviaaChromeextension,whichmeans,obviously,itisChromeonly
-ItsupportsmostoftheplatformssupportedbyPhoneGap$cordovaripple[platform]
TheRippleUI
TheRippleUI
ResponsiveInspector
-AllowsviewingdefinedmediaqueriesofHTMLpages-Usefulwhendevelopingresponsiveweblayouts
-AvailableasaChromeextension
ResponsiveInspectorUI
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
EmulatorvsDevice-Emulatorsallowyoutomakeafirstcheckandfixthemost
obviousbugs-Emulatorsoffera(relatively)easywaytorunappson
multipleplatforms-Devicesallowtorunrealtests
-Devicesfragmentationdon'tallowyoutoruntestsonallthedevices
-Bugsenseandcrowdtestingcanhelpdeveloperstodeployreliableapps
CordovaCLI-Youcanrunthemaincommandsfromanyfolder-Whenworkingonaspecifictargetplatformrunthe
commandscontainedinthecordovafolder-Keepdevicesconnectedtoyourdevenvironmentinorder
totestoften
PhoneGap
PhoneGapArchitecture
PhoneGapEvent
PhoneGapEventFlow
PerformanceTips-Avoidembedandinlinescripts-Minimizerepaintsandreflows
-MinimizeHTMLfiles-CompressandcombineJavaScriptandCSSfiles
-UseCSSsprites
CompressionsTools-Thereareseveralcompressiontools(YUICompressor,
JSMin,Closure,KJScompress,bananascript)-UglifyJS2startedtobeprettyfamoussincejQuerystarted
touseit-Verysimpletoinstallandtouse
$npminstalluglify-js-g
$catfile1.jsfile2.js|uglifyjs--inline-script-omytest.min.js
ClientSideTemplating
Adocumentthatcontainsparameters,identifiedbysomespecialsyntax,thatarereplacedbyactualargumentsbythetemplate
processingsystem
-Itisagreatwaytoseparatemarkupandlogicinviews-It'sduetoshiftoftheapplogicfromservertoclient
TemplatingEngines-underscore.js,templatesarefastandlightweight
-ICanHaz.js,returnsjQueryobject-GoogleClosureTemplates,robustandreliable
-Mustache.js,nologicinthetemplatesthatarelanguageagnostic
-Evenmore...
TemplateandDataAtemplateanditsdatalooklikethefollowingsnippets:
<h1>{{title}}</h1><ul>{{#names}}<li>{{name}}</li>{{/names}}</ul>
vardata={"title":"Story","names":[{"name":"Tarzan"},
UsingTemplates-Atemplatecanbeloadedonruntimeorcompiledand
storedinavariable-Ausefultooltocompilethetemplateasavariableis
pistachio$npminstallpistachio-g
$pistachio--out=splash-tpl.jssplash-tpl.htmlJavaScriptAMD
JavaScriptAMDSpecifiesamechanismfordefiningmodulessuchthatthemoduleand
itsdependenciescanbeasynchronouslyloaded
-Wellsuitedforthebrowserwheresynchronousloadingincursperformance,usability,debugging,andcross-domainaccess
problems
• Dojo:dojo.require('some.module')
• LABjs:$LAB.script("some/module.js')
• CommonJS:require('some/module').
Require.js-JavaScriptfileandmoduleloader-Optimizedforin-browseruse,butitcanbeusedinotherJSenvironments
<scriptdata-main="js/app"src="js/libs/require/require.js"></script>
www/|--js/||--app.js||--main.js||--libs/
AnatomyofaModule1/2
-EachmoduleisdefinedinaseparateJavaScriptfile-Amoduleisdefinedusingthedefinekeywordandreturnsomething
define({color:"black",size:"unisize"
AnatomyofaModule2/2
-Somedefine()callsthatincludeanameforthemoduleasthefirstargument-Ifthemodulehasdependencies,thefirstargumentshouldbeanarrayofdependencynames,andthesecondargumentshouldbeadefinitionfunction
Usingtherequire.jssyntaxcreateanewPhoneGap
applicationthatreactstothedevicereadyevent.
LocalStorage-TheLocalStorageAPIispartoftheWebStorageAPIdefinedbytheW3Cinordertoprovideaguidelineforpersistentdatastorageofkey-
valuepairdatainwebclients
-LocalStorageAPIisdesignedtosupportdatathatneedstobeavailablebetweensessions
ThelocalStorageObject
Itexposesseveralpropertiesandmethods:
• key:returnsthenameofthekeystoredataspecificposition• getItem:returnstheitemidentifiedbyakey• setItem:savessomedatainaspecifickey(i.e.astring)ofthelocalStorageobject
TheStorageEventObject
EachtimethelocalStorageobjectisupdatedaStorageEventisfired.Thiseventcannotbecancelledandcontainsthefollowingproperties:
• key:astringthatrepresentsthenamedkeythatwasadded,removed,ormodified• oldValue:thepreviousvalueofthenamedkeyifitwasupdatedornull
LocalStorageDrawbacks
-TheAPIissynchronousandforthisreasontheappappearslessresponsivebecausethetimeneededtoaccessthelocalStorageobjectisgreaterthantheoneneededtoaccessanobjectinmemory
-Complexdataneedstobeserializedandde-serializedimpactingtheresponsivenessoftheapp
Createasampleappabletostoreinthelocalstoragepreviouslytypedwordssothattheendusercaneasily
getsomesuggestionsthenexttimeisusingtheapp
SQLStorage-PhoneGapprovidesSQLstorageAPIbasedontheWebSQL
specification-WhenadevicealreadyofferssupportforWebSQLtheapp
willuseitotherwisetheappwillusethePhoneGapone-Asadeveloperyouwillnotnoticeanydifference,because
youwillnothavetochangeanylineofcode
CreatetheAppDatabase
InordertostarttoworkwithaDatabaseobjectit’senoughtostoreinavariablewhat’sreturnedbytheopenDatabasemethod
varsize=(1024*1024*2);vardb=window.openDatabase("test","1.0","TestDB",size);
TheopenDatabasemethodacceptsfourarguments;thenameofthe
TheDataBaseObject
TheDataBaseobjectreturnedbytheopenDatabasemethodexposestwomethods:
• transaction->executeanSQLtransaction• changeVersion->changestheversionofthedb(usefulwhenupdatingaschema)
TheSQLTransactionObject
Theobjectisreturnedasanargumentinthefunctiondefinedasfirstargumentofthetransactionmethod
TheexecuteSqlmethodallowsexecutingSQLqueries:
functioncreateTables(transactionObj){
ArgumentsandtheQuery
Youcanuseplaceholderstopassargumentstoaquerywhenusingthetransactionmethod
functionaddData(name,surname,gender){
db.transaction(function(transactionObj){
varsql='INSERTINTOusers(name,surname,gender)VALUES(?,?,?);';
TheSQLResultSetObject
WhenaSQLTransactionobject'sexecuteSqlmethodiscalled,thespecifiedcallbackexecuteswithaSQLResultSetparametercontainingthreeproperties:
• TheinsertIdreturnstherownumberofasuccessfullySQLinsertionstatement
TheSQLResultSetRowListTheSQLResultSetRowListcontainsthedatareturnedfromaSQLselectstatement,theobjectexposes:
functionquerySuccess(tx,results){varlen=results.rows.length;for(vari=0;i<len;i++){
• Thelengthpropertyindicatinghowmanyrowstheselectstatementreturns• Theitemmethodtorecoverdataataspecificindex
DataBaseLimitations
LimitationsarenotrelatedtoPhoneGapitselfbutareduetotheWebViewimplementationofeachtargetplatform
• ThesizelimitvariesaccordinglytotheOSfrom5to25Mb• SinceiOS5.xdatabaseshavebeenmovedtothefolder~/Library/Cachesfrom~/Library/WebKit
Createasampleappabletostoreandreadsomedatafromalocaldatabase
AccelerometerTheaccelerometerisactuallymadeupofthreeaccelerometersandeachonemeasuresthechangesinvelocity(i.e.,linearacceleration)overtimealongthelinearpathontheaxisx,y,andz
AccelerometerObject
Theaccelerometerdetectsthevaluesofthedeltamovementrelativetothecurrentdeviceposition
YoucandetectthedeviceaccelerationdatausingthemethodgetCurrentAccelerationorsettingupawatcherthroughthemethodwatchAcceleration
Inordertostopwatchingtheaccelerometerdatait’senoughtocall
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);
Createasampleapptodetectdeviceshakesusinganumericvalueasboundbetweenthepreviousandactual
positionofthedevice
CompassThePhoneGapCompassAPIallowsyoutoobtainthedirectionthatthedeviceispointingto
TheCompassAPIisavailableonthecompasspropertyofthenavigatorobjectandexposesthefollowingmethods:
• compass.getCurrentHeading,readsthecurrentcompassheadingthroughahandler• compass.watchHeading,readsthecompassheadingataspecifictimeintervalthroughanhandlerandreturnareferencetoit
CompassHeadingObject
It'sreturnedasanargumentinthesuccesshandlerofthewatchHeadingandgetCurrentHeadingmethods,theobjectexposesthefollowingproperties:
• magneticHeading,theheadingindegreesfrom0to359.99• trueHeading,theheadingrelativetothegeographicNorthPole
CompassErrorObject
TheCompassErrorobjecthasapropertynamedcodethatreturnstwopossiblevaluesCompassError.COMPASS_INTERNAL_ERRorCompassError.COMPASS_NOT_SUPPORTED
functiononCompassError(error){
switch(true){
Considerthefollowingsnippetofcode,whichwillgiveyoutherightrotationforthecompass,andcreateasampleappshowinga
GeolocationThetermgeolocationisusedinordertorefertotheidentificationprocessofthereal-worldgeographiclocationofanobject
Thelocationofadeviceisrepresentedthroughapoint,thepointiscomprisedoftwocomponents:latitudeandlongitude
GeolocationAPITheGeolocationAPIisexposedthroughthegeolocationobjectchildofthenavigatorobjectandconsistsofthreemethods:
• getCurrentPosition(),returnsthedeviceposition• watchPosition(),watchesforchangesofthedeviceposition• clearWatch(),stopsthewatcherfordevice’spositionchanges
PositionObjectAccessingitspropertiesyoucanreadthedevice’scoordinatesandthecreationtimestampoftheobjectthatstoresthecoordinates
functiononSuccess(position){
console.log('Coordinates:'+position.coords);console.log('Timestamp:'+position.timestamp);
}
PositionErrorObjectItcontainstwopropertiesthecodeandthemessageone.
functiononError(error){switch(true){caseerror.code==PositionError.PERMISSION_DENIED://Theuserdeniestheapptousethedevice’scurrentpositionbreak;
caseerror.code==PositionError.POSITION_UNAVAILABLE://Thepositionofthedevicecannotbedeterminedbreak;
Camera&CaptureThemaindifferencebetweentheseAPIsisthattheCameraAPIcanaccessonlythedefaultdevicecameraapplicationwhereastheCaptureAPIcanalsorecordaudioorvideo
CaptureAPIallowsmultiplecaptureswithasingleAPIcall
TheCaptureAPIisanimplementationofanabandonedW3Cstandardsdraft
AccessingtheCameraTheCameraAPIexposestwomethodsdefinedinthenavigator.cameraobject:
• getPicture,whichopensthedefaultcameraapplicationorletstheuserbrowsethemedialibrarydependingontheoptionsspecifiedintheconfigurationobjectthemethodacceptsasargument• cleanup,whichcleansuptheimagefilestoredintothetemporarystoragelocation
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,
CapturinganImagevarcameraOptions={targetWidth:300,targetHeight:400,saveToPhotoAlbum:true,allowEdit:true};
navigator.camera.getPicture(onCameraSuccess,onCameraError,cameraOptions);functiononCameraSuccess(imageData){
//Usetheimagedata
}
functiononCameraError(error){
CaptureAPITheCaptureAPIworksasynchronouslyasmostofthePhoneGapAPIsandprovidesaccesstotheaudio,image,andvideocapturecapabilitiesofthedevice
varcapture=navigator.device.capture;capture.captureImage(function(files){
• captureVideo• captureAudio• captureImage
MediaFileObjectTheMediaFileobjectstoredinthefilesarrayreturnedinthesuccesshandlerdescribesthecapturedmedia
• fullPath,astringrepresentingthefilepathonthedeviceincludingthefilename• lastModifiedDate,modificationdateofthefileexpressedinmssinceJanuary1,1970• name,astringrepresentingthenameofthefile• size,anumberrepresentingthesizeofthefileinbytes
CaptureOptions• CaptureVideoOptions(limitandduration)• CaptureImageOptions(limit)• CaptureAudioOptions(limitandduration)
CaptureErrorObject• CaptureError.CAPTURE_INTERNAL_ERR• CaptureError.CAPTURE_APPLICATION_BUSY• CaptureError.CAPTURE_INVALID_ARGUMENT• CaptureError.CAPTURE_NO_MEDIA_FILES• CaptureError.CAPTURE_NOT_SUPPORTED
Createasampleappabletocaptureanimageandapplythegrayscaleeffectyoucanfindhere
http://www.html5rocks.com/en/tutorials/canvas/imagefilters/.
UnderstandingtheAPI
ThePhoneGapFilesAPIisanimplementationoftwodifferentW3CAPIs,theDirectoriesandSystemAPIandtheFileAPI
ThePhoneGapFilesAPIisnotacompleteimplementationoftheW3Cspecification,themissingpieceisthesynchronousfilesysteminterfaceimplementation
AccessingtheFileSystem
InordertoaccessthedevicefilesystemyoucanusetherequestFileSystemmethodoftheLocalFileSystemobject
Themethodacceptsfourarguments:
• Thetypeofstorage(temporaryorpersistent)• Theamountofspaceinbytestobeallocatedonthedevice
StorageTypes
Thedeviceharddiskisnotcompletelyopentotheapp’sview.Alimitedportionoftheharddiskisdedicatedtoasingleappalone;thisistheappsandbox.
• LocalFileSystem.PERSISTENTindicatesthatthestoragecannotberemovedbytheuseragentwithouttheapp’soruser’spermission• LocalFileSystem.TEMPORARYindicatesthatthefilesstoredintherequestedspacecanbedeletedbytheuseragentorbythesystemwithouttheapp’soruser’spermission
ReadingDirectories&Files
functiononSuccess(fileSystem){
varcurrentRoot=fileSystem.root;
vardirectoryReader=currentRoot.createReader();directoryReader.readEntries(onDirSuccess,onFileSysError);
}
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)
WritingDataTowritedatatoafileitsufficesthattheappgetsaccesstothefileusingtheFileWriterobject
TogetaFileWriterobjectyoufirsthavetogetaccesstoaDirectoryEntryortoaFileEntryobjectusingtherequestFileSystemmethod
Onceyousuccessfullygetaccesstothefilesystemyoucanrequestafilespecifyingthatyouwanttocreateitusingthecreateflag
functiononFileSystemSuccess(fileSystem){
CreatingaWriterInthesuccesshandlerit'spossibletocreateawriter,thecreateWritermethodalsorequiresthesuccessandfailurehandlers
functiononGetFile(file){
file.createWriter(onGetWriter,onGetWriterError);
}
functiononGetWriter(writer){
writer.write('HelloPhoneGapFilesAPI!');
EventsDuringthewriteoperationseveraleventsoccur;foreacheventthereisacorrespondingpropertydefinedontheFileWriterobject:
• onwritestartiscalledwhentheFileWriterobjectstartstowritethefile• onwriteiscalledwhentheFileWriterobjecthascompletedsuccessfullythewriteoperation• onabortiscalledwhenthewriteoperationhasbeeninterrupted
ReadingDataOnceyouhaveaccesstothefileyoucancreateaFileReaderobjectanduseitsmethods:
• readAsDataURL,readsfileandreturndataasabase64-encodeddataURL• readAsText,readstextfile• readAsBinaryString,readsfileasbinaryandreturnsabinarystring• readAsArrayBuffer,readsfileasanArrayBuffer
DownloadandUpload
OnceyougetaccesstothefilesystemcreateanewFileTransferobjectandcallthedownloadmethodspecifyingtheremoteURL,thesystemfilepathURI,andthesuccessfailurehandlers
varft=newFileTransfer();ft.upload(fileURI,encodeURI("http://some.server.com/upload.php"),onSuccess,onError,options);
FileUploadOptions• fileKey:thenameoftheformelement.Defaultstofile• fileName:thefilenametousewhensavingthefileontheserver.• mimeType:themimetypeofthedatatoupload• params:asetofoptionalkey/valuepairstopassintheHTTPrequest• chunkedMode:whethertouploadthedatainchunkedstreamingmode
Createasampleappandrenderaprogressbarindicatingtheamountoffiledownloadedfromaremoteserver
ContactNameObject
• formatted,representsthecompletenameofthecontact• familyName,representsthecontact’sfamilyname• givenName,representsthecontact’sgivenname• middleName,representsthecontact’smiddlename• honorificPrefix,representsthecontact’sprefix(e.g.,Mr.orDr.)
ContactFieldObject• type,astringthatrepresentsthetypeoffield,possiblevaluesarehome,work,mobile,andsoon• value,astringrepresentingthevalueofthefieldsuchasaphonenumberoremailaddress• pref,aBooleanvaluethatindicatesifinaspecificfieldisreturnedtheuserpreferredvalue
ContactAddressObject
• pref,aBooleanthatindicateswhetherthereturnedContactAddressisthepreferredvalueoftheuserfortheContactAddressobject• type,astringthatindicateswhattypeofaddressisstoredintheContactAdressobject(e.g.,home,office,etc.)• formatted,astringthatrepresentsthecompleteaddress
ReadaContactObject
Createacontact:varcontact=navigator.contacts.create({'displayName':'Giorgio'});
contact.save(onContactSaved,onContactSavedError);contact.remove(onContactRemoved,onContactRemovedError);
Findacontact:varoptions=newContactFindOptions();
WhatisaPluginIt'sanativecodeexposedtotheappusingJavaScript
Thenativepartextendsorimplementsplatformspecificclassesorinterfaces(e.g.CordovaPlugin,CDVPlugin,etc.)
Aplugincanbeinstalledanduninstalledusingcordova-cliorplugmansadas
PhoneGapArchitecture
PlugmanPlugmanisanopensourcecommandlineutilitydistributedasannpmmoduletofacilitatetheinstallationanduninstallationofplugins
ItsupportstheAndroid,BlackBerry10andiOSplatforms
Onceinstalledyoucanuseseveralcommandsfromyourcommandlinetool
PlugmanCommands
$plugman--fetch
$plugman--platformandroid--projectPLATFORM_PROJECT_PATH--plugin
$plugman--prepare
$plugman--platformandroiduninstall--projectPLATFORM_PROJECT_PATH--plugin
BuildingBlocksofaPlugin
APhoneGappluginisabridgebetweentheWebViewandthenativeplatformtheappisrunningon
TheonlymandatoryimplementationisthewaytocommunicatebetweenJavaScriptandthenativeenvironmentusingthecordova.execfunction
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
Book(s)
top related