1 / 42

PhoneGap Hardware Manipulation

PhoneGap Hardware Manipulation. Accessing the device native APIs. Kamen Bundev. Telerik Academy. academy.telerik.com. Senior Front-End Developer. http://www.telerik.com. Table of Contents. The Device Object Notification API Connection API Events deviceready event pause/resume events

matia
Download Presentation

PhoneGap Hardware Manipulation

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PhoneGap Hardware Manipulation Accessing the device native APIs KamenBundev Telerik Academy academy.telerik.com Senior Front-End Developer http://www.telerik.com

  2. Table of Contents • The Device Object • Notification API • Connection API • Events • deviceready event • pause/resume events • online/offline events • Battery events • Button events • Compass • Accelerometer • Geolocation • Camera • Contacts • Summary

  3. Last time you've learned what PhoneGap is and how to compile your first mobile application with its SDK. Today we will delve deeper into its APIs to try and test its capabilities.

  4. The Device Object • Holds the description of the device hardware and software, theapplication is currently running on: { name= Device Model Name, phonegap= PhoneGap version, platform= returns the OS platform name, uuid= returns an unique device ID, version= returns OS version }

  5. Notification API • The Notification API • Initialized as navigator.notification • Holds several utility functions, oriented at showing or playing different user notifications • The available methods are: navigator.notification= { alert(message, alertCallback, [title], [buttonName]), confirm(message, confirmCallback, [title], [buttonLabels]), vibrate(milliseconds), beep(times)}

  6. Connection API • The Connection API • Available under navigator.network • Holds a single property – type • Can be used to determine the network/internet connectivity

  7. Connection API (2) • When the application is initialized, network.connection.typecan be: Connection.NONE - No network connection detected Connection.ETHERNET - LAN network connection Connection.WIFI- Wireless B/G/N connection type Connection.CELL_2G - 2G connection type- GPRS or EDGE (2.5G) Connection.CELL_3G - 3G HSPA connection type Connection.CELL_4G - LTE or WiMax connection type Connection.UNKNOWN - the connection type cannot be determined

  8. Connection API (3) function checkConnection() {varnetworkState = navigator.network.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.NONE]     = 'No network connection';    alert('Connection type: ' + states[networkState]);}checkConnection();

  9. Events • There are numerous events fired at different stages of PhoneGap'slifecycle • One of these events is fired during initialization, • Others - when certain hardware events happen • You can attach event handlers to these events in order to handle your application init or feedback

  10. The deviceready event • Fired when PhoneGap finishes its initialization • You can use it to run the various PhoneGap specific functions that require their back-ends to be ready document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // Fill out the PhoneGap version $("#phonegap_version").text(device.phonegap); }

  11. The pause/resume events • Due to limited resources on mobile phones (mostly RAM), when you switched out of an application • The OS freezes the app in background (pauses it) and later restores it when you focus it back • If the OS needs additional resources during this frozen state, it may kill the application completely • These two events are fired when the state changes, the developer can for instance stop some battery consuming services on pause or maybe check for new data on resume

  12. The pause/resume events (2) document.addEventListener("pause", onPause, false); document.addEventListener("resume", onResume, false); function onPause() { navigator.compass.clearWatch(compassId); } function onResume() { compassId= navigator.compass .watchHeading( function (heading) { // do something }); }

  13. The online/offline Events • Fired when the user connects or disconnects to internet • Naturally you will use them only if you want to be aware when internet connection is available document.addEventListener("online", onOnline, false); document.addEventListener("offline", onOffline, false); function onOnline() { // Handle the online event } function onOffline() { // Handle the offline event }

  14. The batterystatus / batterylow / batterycriticalevents • Group of events, fired when a battery incident arises • The batterylow and batterycritical events are fired when the battery state reaches a certain level (device specific) • The batterystatus event is fired when the battery level changes with 1% or when the device's charger is plugged or unplugged

  15. The batterystatus / batterylow / batterycritical events (2) • All these events receive an object with two properties, when fired - level (battery level from 0-100) and isPlugged- boolean. window.addEventListener("batterystatus", onBatteryStatus, false); function onBatteryStatus(info) { console.log("Level: " + info.level + " isPlugged: " + info.isPlugged); }

  16. The Button Events • Called when the user presses one of the phone's hardware buttons • These events are available only in Android and BlackBerry, limited to which buttons are available in the platform. backbutton(Android and BlackBerry)menubutton(Android and BlackBerry)searchbutton(Android)startcallbutton(BlackBerry)endcallbutton(BlackBerry)volumedownbutton(BlackBerry)volumeupbutton(BlackBerry)

  17. Compass (1) • Most smartphone devices these days and even the newer featurephones have an embedded magnetometer • Can be used to obtain the current device heading according to the magnetic North of planet Earth

  18. Compass (2) • The Compass object dwells under the window.navigatorobject and sports the following properties and methods: navigator.compass = { getCurrentHeading(compassSuccess, [compassError], [compassOptions]), intwatchHeading(compassSuccess, [compassError], [compassOptions]), clearWatch(watchId), intwatchHeadingFilter(compassSuccess, [compassError], [compassOptions]), // Only on iOS. clearWatchFilter(watchId) // Only on iOS. }

  19. Compass (3) • compassSuccessreceives one parameter - the current heading object, which consists of: CompassHeading = { magneticHeading: The heading in degrees from 0-359.99, trueHeading: The heading relative to the geographic North in degrees 0-359.99. A negative value indicates that the true heading could not be determined. Some platforms return directly the magnetic heading instead, headingAccuracy: The deviation in degrees between the reported heading and the true heading, timestamp: The timestamp of the reading }

  20. Compass (4) • compassError also receives one parameter with only one property: • compassOptions can contain additional options passed to the magnetometer: CompassError = { code: The reported error code. Can be one either COMPASS_INTERNAL_ERR or COMPASS_NOT_SUPPORTED } CompassOptions = { frequency: How often to retrieve the compass heading in milliseconds - default: 100, filter: The change in degrees required to initiate a watchHeadingFilter success callback // Only on iOS. }

  21. Compass Example function onSuccess(heading) { varelement = document.getElementById('heading'); element.innerHTML= 'Heading: ' + heading.magneticHeading; } function onError(compassError) { alert('Compass error: ' + compassError.code); } varoptions = { frequency: 3000 }; // Update every 3 seconds varwatchID = navigator.compass.watchHeading(onSuccess, onError, options);

  22. Accelerometer (1) • Accelerometers lately are getting cheaper by the dozen and are even more common than magnetometers in modern phones. • The accelerometer object is instantiated under window.navigator and includes the following methods and properties: navigator.accelerometer = { getCurrentAcceleration(accelerometerSuccess, [accelerometerError]), intwatchAcceleration(accelerometerSuccess, [accelerometerError], [accelerometerOptions]), clearWatch(watchId) }

  23. Accelerometer (2) • When accelerometerSuccess gets called, PhoneGap passes it an object with several properties: • accelerometerError gets called when the acceleration reading fails. It doesn't have arguments. • In accelerometerOptions you can specify the frequency to retrieve the Acceleration in milliseconds. The default is 10 seconds (10000ms). Acceleration = { x: Amount of motion on the x-axis - range [0, 1], y: Amount of motion on the y-axis - range [0, 1], z: Amount of motion on the z-axis - range [0, 1], timestamp: Reading timestamp in milliseconds }

  24. Accelerometer Example 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('Error!'); } varoptions = { frequency: 3000 }; // Update every 3 seconds, watchID= navigator.accelerometer.watchAcceleration (onSuccess, onError, options);

  25. Geolocation (1) • PhoneGap includes Geolocation API to connect to the device GPS and read the latitude and longitude of the current geographic location. • Besides the device GPS, common sources of locationinformation can be • GeoIPdatabases, • RFID, WiFi and Bluetooth MAC addresses, • GSM/CDMA cell IDs , • The returned location can be inaccurate due to the current device positioning method.

  26. Geolocation(2) • The Geolocation API resides in the window.navigator object. navigator.geolocation = { getCurrentPosition(geolocationSuccess, [geolocationError], [geolocationOptions]), intwatchPosition(geolocationSuccess, [geolocationError], [geolocationOptions]), clearWatch(watchId) }

  27. Geolocation(3) • When PhoneGap calls geolocationSuccess, it feeds it with the following position object: Position = { coords: { latitude: Latitude in decimal degrees, longitude: Longitude in decimal degrees, altitude: Height in meters above the ellipsoid, accuracy: Accuracy level of the coordinates in meters, altitudeAccuracy: Accuracy level of the altitude in meters, heading: Direction of travel, specified in degrees clockwise relative to the true north, speed: Current ground speed of the device, in m/s }, timestamp: The timestamp when the reading was taken. }

  28. Geolocation(4) • When an error occurs, PhoneGap passes the following error object to geolocationError callback: PositionError = { code: One of the predefined error codes listed below, message: Error message describing the details of the error encountered, can be one of PERMISSION_DENIED, POSITION_UNAVAILABLE, TIMEOUT }

  29. Geolocation(5) • You can adjust the accuracy of the readings using the geolocation options as the last argument: GeolocationOptions = { frequency: How often to retrieve the position in milliseconds, deprecated, use maximumAge instead - default 10000, enableHighAccuracy: Provides a hint that the application would like to receive the best possible results, timeout: The maximum timeout in milliseconds of the call to geolocation.getCurrentPosition or geolocation.watchPosition, maximumAge: Don't accept a cached position older than the specified time in milliseconds }

  30. GeolocationExample // onSuccessCallback varonSuccess = 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: ' + new Date(position.timestamp) + '\n'); }; // onError Callback receives a PositionErrorobject function onError(error) { alert('code: ' + error.code+ '\n' + 'message: ' + error.message + '\n'); } navigator.geolocation.getCurrentPosition(onSuccess, onError);

  31. Camera (1) • Provides access to the device camera • Resides in window.navigator and has just one method to work with: • Takes a photo using the camera or retrieves a photo from the device's album. The image is returned as a base64 encoded String or as the URI of the image file. navigator.camera.getPicture(onSuccess, onFail, [Settings]);

  32. Camera (2) • Optional parameters to customize the camera settings: cameraOptions = { quality: Quality of saved image - range [0, 100], destinationType: DATA_URL or FILE_URI, sourceType: CAMERA, PHOTOLIBRARY or SAVEDPHOTOALBUM, mediaType: PICTURE, VIDEO, ALLMEDIA, allowEdit: Allow simple editing of image before selection, encodingType: JPEG or PNG, targetWidth: Width in pixels to scale image, targetHeight: Height in pixels to scale image };

  33. Camera Example navigator.camera.getPicture(onSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI }); function onSuccess(imageURI) { var image = document.getElementById('myImage'); image.src = imageURI; } function onFail(message) { alert('Failed because: ' + message); }

  34. Contacts (1) • Provides access to the device contacts DB. • Initialized as navigator.contacts. • Use the create() method to create a new contact object and then the save() method in it to save it to the phone database • Use the find() method to filter contacts and get the fields you need. navigator.contacts = { create(properties), find(contactFields, contactSuccess, [contactError], [contactFindOptions]) } contact = navigator.contacts.create({"displayName": "Test User"});

  35. Contacts (2) • contactSuccess returns an object or array of objects with the following fields (if requested) Contact = { id: Unique identifier, displayName: User friendly name of the contact, name: A ContactName object containing the persons name, nickname: A casual name to address the contact by, phoneNumbers: A ContactFieldarray of all phone numbers, emails: A ContactField array of all email addresses, addresses: A ContactAddress array of all addresses, ims: A ContactFieldarray of all the contact's IM addresses, organizations: A ContactOrganization array of all organizations, birthday: The birthday of the contact, note: A note about the contact, photos: A ContactFieldarray of the contact's photos, categories: AContactFieldarray of all user categories, urls: AContactFieldarray of contact’s web pages }

  36. Contacts (3) • There are also three methods in the Contact object : • ContactName object consists of: ContactName = { formatted: The complete name of the contact, familyName: The contacts family name, givenName: The contacts given name, middleName: The contacts middle name, honorificPrefix: The contacts prefix (example Mr. or Dr.), honorificSuffix: The contacts suffix (example Esq.) } { save(onSuccess, [onError]) – saves the contact in the device, clone() – clones the contact and sets its ID to null, remove(onSuccess, [onError]) – removes a contact }

  37. Contacts (5) • ContactAddress consists of the following fields: ContactAddress = { type: A string that tells you what type of field this is (example: 'home'), formatted: The full address formatted for display, streetAddress: The full street address, locality: The city or locality, region: The state or region, postalCode: The zip code or postal code, country: The country name }

  38. Contacts (6) • ContactOrganization field consists of the following properties: • And finally ContactField has only two: ContactOrganization = { type: The field type(example: ‘remote'), name: The name of the organization, department: The department the contract works for, title: The contacts title at the organization. } ContactField = { type: The field type (example: ‘office'), value: The value of the field (such as a phone number or email address) }

  39. Contacts (7) • contactError receives an error object with one of the following error codes: • contactFields is a requred parameter of the find() method, specified as an array of strings: • contactFindOptions is optional, but you can specify additional find settings with it: ["name", "phoneNumbers", "emails"] ContactError.UNKNOWN_ERROR, ContactError.INVALID_ARGUMENT_ERROR, ContactError.TIMEOUT_ERROR, ContactError.PENDING_OPERATION_ERROR, ContactError.IO_ERROR, ContactError.NOT_SUPPORTED_ERROR, ContactError.PERMISSION_DENIED_ERROR ContactFindOptions = { filter: Search string to filter contacts- default "", multiple: Should return multiple results – default false }

  40. Contacts Example function onSuccess(contacts) { alert('Found ' + contacts.length + ' contacts.'); }; function onError(contactError) { alert('onError!'); }; // find all contacts with 'Bob' in any name field var options = new ContactFindOptions(); options.filter="Bob“, fields = ["displayName", "name"]; navigator.contacts.find(fields, onSuccess, onError, options);

  41. Summary • Today we covered part of the PhoneGap APIs, but there are still some left. As a homework, take a look at http://docs.phonegap.com • Read about the following APIs: • Storage • Capture • Media • File

  42. Homework • Write a small PhoneGap & jQuery Mobile application which should present a form to enter all data of a contact and then add it to the phone database. All the new contacts should have the same note. • Show in a list the saved contacts (filter them with the note) with a detail view, where all the previously entered data is shown.

More Related