Upgrade to Pro — share decks privately, control downloads, hide ads and more …

PhoneGap Deep Dive

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.

E47af1013d3ab2bd530c8b87010074b4?s=128

Chris Griffith

July 17, 2013
Tweet

Transcript

  1. @ChrisGriffith  

  2. These  opinions  and  thoughts  are  my  own,  and   may

     or  may  not  reflect  the  opinions  of  the   company  that  I  work  for.   Disclaimer  
  3. None
  4. ApplicaAon  container  that  allows  you  to  build   naAvely  installed

     apps  using  HTML,  CSS  &  JavaScript       What  is  PhoneGap?  
  5. Ge/ng  Started   cordova.apache.org  

  6. •  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  
  7. •  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  
  8. •  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  
  9. <script src="phonegap.js"></script> Secret  Sauce  

  10. <!DOCTYPE html> <html> <head> <title>PhoneGap Example</title> <script src="phonegap.js"></script> <script> //

    Wait for PhoneGap to load document.addEventListener("deviceready", onDeviceReady, false);
  11. Device   The  device  object  describes  the  device's   hardware

     and  soTware.  
  12. // 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>
  13. 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  
  14. 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]); }
  15. GeoLocaAon  

  16. 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.  
  17. 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  
  18. None
  19. geolocaAon.getCurrentPosiAon   Returns  the  device's  current  posiAon  as  a  

    PosiAon  object.     navigator.geolocation.getCurrentPosition(geo locationSuccess, [geolocationError], [geolocationOptions]);
  20. // 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);
  21. Compass   Obtains  the  direcAon  that  the  device  is  poinAng.

     
  22. 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); }
  23. Accelerometer  

  24. None
  25. None
  26. Accelerometer   Captures  device  moAon  in  the  x,  y,  and

     z  direcAon.     Methods       accelerometer.getCurrentAcceleraAon   accelerometer.watchAcceleraAon   accelerometer.clearWatch     Arguments       accelerometerSuccess   accelerometerError   accelerometerOpAons  
  27. 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);
  28. Events   •  deviceready   •  pause   •  resume

      •  online   •  offline   •  backbunon   •  banerycriAcal   •  banerylow   •  banerystatus   •  menubunon   •  searchbunon   •  startcallbunon   •  endcallbunon   •  volumedownbunon   •  volumeupbunon  
  29. document.addEventListener("offline", onOffline, false); function onOffline() { // Handle the offline

    event } document.addEventListener("online", onOnline, false); function onOnline() { // Handle the online event }
  30. File   This  object  contains  anributes  of  a  single  file.

       
  31. Storage   Embedded  SQLite  database     or    

    localStorage  
  32. localStorage   Provides  access  to  a  W3C  Storage  interface  

      (hnp://dev.w3.org/html5/webstorage/#the-­‐ localstorage-­‐anribute)  
  33. 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 }
  34. Embedded  SQLite  database   var  dbShell  =   window.openDatabase(database_name,  

    database_version,  database_displayname,   database_size);  
  35. 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);
  36. Camera   The  camera  object  provides  access  to  the  

    device's  default  camera  applicaAon.  
  37. 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.  
  38. 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 };
  39. 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).    
  40. capture.captureAudio   Start  the  audio  recorder  applicaAon  and  return  

    informaAon  about  captured  audio  clip  file(s)  
  41. // 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});
  42. 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});
  43. capture.captureVideo   Start  the  video  recorder  applicaAon  and  return  

    informaAon  about  captured  video  clip  file(s).  
  44. 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]);
  45. // 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);
  46. notification.alert notification.confirm notification.prompt notification.beep notification.vibrate NoAficaAons  

  47. 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  
  48. None
  49. // 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 );
  50. 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  
  51. None
  52. // 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 ); }
  53. 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  
  54. None
  55. // 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 ); }
  56. navigator.notification.beep(times); Beep  

  57. 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.  
  58. navigator.notification.vibrate(mseconds) Vibrate  

  59. Push  NoAficaAons  

  60. Push  NoAficaAons  Flow  

  61. 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  
  62. hHp://docs.phonegap.com/en/2.9.0/index.html   Further  resources   PhoneGap  API  Explorer  App  (iOS

     &  Android)  
  63. Now  go  build  something!  

  64. Thanks!   chris.griffith@gmail.com   @chrisgriffith   hnp://chrisgriffith.wordpress.com/