$30 off During Our Annual Pro Sale. View Details »

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.

Chris Griffith

July 17, 2013
Tweet

More Decks by Chris Griffith

Other Decks in Technology

Transcript

  1. @ChrisGriffith  

    View Slide

  2. These  opinions  and  thoughts  are  my  own,  and  
    may  or  may  not  reflect  the  opinions  of  the  
    company  that  I  work  for.  
    Disclaimer  

    View Slide

  3. View Slide

  4. ApplicaAon  container  that  allows  you  to  build  
    naAvely  installed  apps  using  HTML,  CSS  &  JavaScript    
     
    What  is  PhoneGap?  

    View Slide

  5. Ge/ng  Started  
    cordova.apache.org  

    View Slide

  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•  Contacts  -­‐  find  and  create  new  friends  
    Features  

    View Slide

  7. •  Device  -­‐  device  and  OS  version  metadata  
    •  Events  -­‐  various  app/hardware  related  
    events  
    •  File  -­‐  naAve  file  system  access  (+  upload)  
    •  Geoloca•  GlobalizaformaRng  
     
    Features  

    View Slide

  8. •  Media  -­‐  related  to  audio  playback  
    (supports  record  as  well)  
    •  No<ficanoAficaAons  
    •  Splashscreen  -­‐  for  your  splash  screen  
    needs  
    •  Storage  -­‐  Mini  database  
    Features  

    View Slide


  9. Secret  Sauce  

    View Slide




  10. PhoneGap Example


    <br/> <br/>// Wait for PhoneGap to load <br/> document.addEventListener("deviceready",<br/>onDeviceReady, false); <br/> <br/> <br/>

    View Slide

  11. Device  
    The  device  object  describes  the  device's  
    hardware  and  soTware.  

    View Slide

  12. // PhoneGap is ready
    function onDeviceReady() {
    var element =
    document.getElementById('deviceProperties');

    element.innerHTML = 'Device Name: ' +
    device.name + '
    ' +
    'Device Cordova: ' + device.cordova + '
    ' +
    'Device Platform: ' + device.platform + '
    ' +
    'Device UUID: ' + device.uuid + '
    ' +
    'Device Model: ' + device.model + '
    ' +
    'Device Version: ' + device.version + '
    ';
    }




    Loading device
    properties...

    View Slide

  13. ConnecThe  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  

    View Slide

  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]);
    }


    View Slide

  15. GeoLocaAon  

    View Slide

  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.  

    View Slide

  17. Accuracy   PosiGPS   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  

    View Slide

  18. View Slide

  19. geolocaAon.getCurrentPosiAon  
    Returns  the  device's  current  posiAon  as  a  
    PosiAon  object.  
     
    navigator.geolocation.getCurrentPosition(geo
    locationSuccess, [geolocationError],
    [geolocationOptions]);

    View Slide

  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);

    View Slide

  21. Compass  
    Obtains  the  direcAon  that  the  device  is  poinAng.  

    View Slide

  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);
    }

    View Slide

  23. Accelerometer  

    View Slide

  24. View Slide

  25. View Slide

  26. Accelerometer  
    Captures  device  moAon  in  the  x,  y,  and  z  direcAon.  
     
    Methods    
     
    accelerometer.getCurrentAcceleraAon  
    accelerometer.watchAcceleraAon  
    accelerometer.clearWatch  
     
    Arguments    
     
    accelerometerSuccess  
    accelerometerError  
    accelerometerOpAons  

    View Slide

  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);

    View Slide

  28. Events  
    •  deviceready  
    •  pause  
    •  resume  
    •  online  
    •  offline  
    •  backbunon  
    •  banerycriAcal  
    •  banerylow  
    •  banerystatus  
    •  menubunon  
    •  searchbunon  
    •  startcallbunon  
    •  endcallbunon  
    •  volumedownbunon  
    •  volumeupbunon  

    View Slide

  29. document.addEventListener("offline",
    onOffline, false);

    function onOffline() {
    // Handle the offline event
    }

    document.addEventListener("online",
    onOnline, false);

    function onOnline() {
    // Handle the online event
    }

    View Slide

  30. File  
    This  object  contains  anributes  of  a  single  file.  
     

    View Slide

  31. Storage  
    Embedded  SQLite  database  
     
    or  
     
    localStorage  

    View Slide

  32. localStorage  
    Provides  access  to  a  W3C  Storage  interface    
    (hnp://dev.w3.org/html5/webstorage/#the-­‐
    localstorage-­‐anribute)  

    View Slide

  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
    }

    View Slide

  34. Embedded  SQLite  database  
    var  dbShell  =  
    window.openDatabase(database_name,  
    database_version,  database_displayname,  
    database_size);  

    View Slide

  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);

    View Slide

  36. Camera  
    The  camera  object  provides  access  to  the  
    device's  default  camera  applicaAon.  

    View Slide

  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.  

    View Slide

  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 };

    View Slide

  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).  
     

    View Slide

  40. capture.captureAudio  
    Start  the  audio  recorder  applicaAon  and  return  
    informaAon  about  captured  audio  clip  file(s)  

    View Slide

  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});

    View Slide

  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});

    View Slide

  43. capture.captureVideo  
    Start  the  video  recorder  applicaAon  and  return  
    informaAon  about  captured  video  clip  file(s).  

    View Slide

  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]);

    View Slide

  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);

    View Slide

  46. notification.alert
    notification.confirm
    notification.prompt
    notification.beep
    notification.vibrate
    NoAficaAons  

    View Slide

  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  

    View Slide

  48. View Slide

  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
    );

    View Slide

  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  

    View Slide

  51. View Slide

  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
    );
    }

    View Slide

  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  

    View Slide

  54. View Slide

  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
    );
    }

    View Slide

  56. navigator.notification.beep(times);
    Beep  

    View Slide

  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.  

    View Slide

  58. navigator.notification.vibrate(mseconds)


    Vibrate  

    View Slide

  59. Push  NoAficaAons  

    View Slide

  60. Push  NoAficaAons  Flow  

    View Slide

  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  

    View Slide

  62. hHp://docs.phonegap.com/en/2.9.0/index.html  
    Further  resources  
    PhoneGap  API  Explorer  App  (iOS  &  Android)  

    View Slide

  63. Now  go  build  something!  

    View Slide

  64. Thanks!  
    chris.griffi[email protected]  
    @chrisgriffith  
    hnp://chrisgriffith.wordpress.com/  

    View Slide