16. PhoneGap Hardware Manipulation - Accessing the device native APIs


Published on

Cross-Platform Mobile Development @ Telerik Academy
Telerik Software Academy: http://mobiledevcourse.telerik.com
The website and all video materials are in Bulgarian
The Device Object
Notification API
Connection API

Published in: Education, Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Когато PhoneGapсе инициализира, той създава няколко обекта (повечето от тях в window.navigator), за да подпомогне комуникацията между вашата апликация и устройството под нея.{ name: Може също да върне име на продукта в Андроид или името на собственика на телефона в iOS, platform: iOSвръща iPhone като име на операционната си система вместо правилното iOS,уникалният идентификатор се генерира по различен начин на всяка платформа version: Windows Phone връща пълната версия, например 7.10.xxxx}
  • Alertи Confirm се предоставени като заместници на системните такива диалози, за да може да се промени изгледът им (имена на бутони, заглавие).Някои платформи не спират изпълнението на джаваскрипт когато показват системните диалози и това е добър начин за заобикалянеъо на този проблем.Във Windows Phone бутоните не могат да се променят.Във iOSPhoneGapигнорира аргументите на vibrate() и beep() – файлът трябва да е по-къс от 30 секунди и да се намира във главната директория на HTML приложението със името beep.wav
  • Има и изключения – някои мобилни операционни системи не спират изпълнението на апликациите и те продължават да работят в background.
  • altitudeAccuracyне се поддържа в Android и винаги ще върне null.
  • Аргумента allowEdit е достъпен само в iOS.quality, mediaTypeиsourceTypeсе игнорират в BlackBerry PalmencodingTypeне се поддържа в Android
  • Категориите се поддържат само вBlackBerry и то само отчасти.
  • 16. PhoneGap Hardware Manipulation - Accessing the device native APIs

    1. 1. PhoneGap Hardware Manipulation Accessing the device native APIsKamen BundevSenior Front-End Developerhttp://www.bundyo.org/Telerik Software Academyhttp://academy.telerik.com
    2. 2. Table of Contents The Device Object  Compass Notification API  Accelerometer Connection API  Geolocation Events  Camera  deviceready event  Contacts  pause/resume events  online/offline events  Summary  Battery events  Button events
    3. 3.  Last time youve 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. 4. The Device Object Holds the description of the device hardware and software, the application 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. 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. 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. 7. Connection API (2) When the application is initialized, network.connection.type can be:Connection.NONE - No network connection detectedConnection.ETHERNET - LAN network connectionConnection.WIFI - Wireless B/G/N connection typeConnection.CELL_2G - 2G connection type- GPRS or EDGE (2.5G)Connection.CELL_3G - 3G HSPA connection typeConnection.CELL_4G - LTE or WiMax connection typeConnection.UNKNOWN - the connection type cannot be determined
    8. 8. Connection API (3)function checkConnection() { var networkState = 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. 9. Events There are numerous events fired at different stages of PhoneGaps lifecycle  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. 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 readydocument.addEventListener("deviceready", onDeviceReady, false);function onDeviceReady() { // Fill out the PhoneGap version $("#phonegap_version").text(device.phonegap);}
    11. 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. 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. 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 availabledocument.addEventListener("online", onOnline, false);document.addEventListener("offline", onOffline, false);function onOnline() { // Handle the online event}function onOffline() { // Handle the offline event}
    14. 14. The batterystatus / batterylow / batterycritical events 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 devices charger is plugged or unplugged
    15. 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. 16. The Button Events Called when the user presses one of the phones 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. 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. 18. Compass (2) The Compass object dwellsunder the window.navigator object and sports the following properties and methods:navigator.compass = { getCurrentHeading(compassSuccess, [compassError], [compassOptions]), int watchHeading(compassSuccess, [compassError], [compassOptions]), clearWatch(watchId), int watchHeadingFilter(compassSuccess, [compassError], [compassOptions]), // Only on iOS. clearWatchFilter(watchId) // Only on iOS.}
    19. 19. Compass (3) compassSuccess receives 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 geographicNorth in degrees 0-359.99. A negative value indicates thatthe true heading could not be determined. Some platformsreturn directly the magnetic heading instead, headingAccuracy: The deviation in degrees between thereported heading and the true heading, timestamp: The timestamp of the reading}
    20. 20. Compass (4) compassError also receives one parameter with only one property:CompassError = { code: The reported error code. Can be one eitherCOMPASS_INTERNAL_ERR or COMPASS_NOT_SUPPORTED} compassOptions can contain additional options passed to the magnetometer:CompassOptions = { frequency: How often to retrieve the compass headingin milliseconds - default: 100, filter: The change in degrees required to initiate awatchHeadingFilter success callback // Only on iOS.}
    21. 21. Compass Examplefunction onSuccess(heading) { var element = document.getElementById(heading); element.innerHTML = Heading: + heading.magneticHeading;}function onError(compassError) { alert(Compass error: + compassError.code);}var options = { frequency: 3000 }; // Update every 3 secondsvar watchID = navigator.compass.watchHeading(onSuccess, onError, options);
    22. 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]), int watchAcceleration (accelerometerSuccess, [accelerometerError], [accelerometerOptions]), clearWatch (watchId)}
    23. 23. Accelerometer (2) When accelerometerSuccess gets called, PhoneGap passes it an object with several properties: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} accelerometerError gets called when the acceleration reading fails. It doesnt have arguments. In accelerometerOptions you can specify the frequency to retrieve the Acceleration in milliseconds. The default is 10 seconds (10000ms).
    24. 24. Accelerometer Examplefunction 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!);}var options = { frequency: 3000 }; // Update every 3 seconds, watchID = navigator.accelerometer.watchAcceleration (onSuccess, onError, options);
    25. 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  GeoIP databases,  RFID, WiFi and Bluetooth MAC addresses,  GSM/CDMA cell IDs , The returned locationcan be inaccurate due to the current device positioning method.
    26. 26. Geolocation (2) The Geolocation API resides in the window.navigator object.navigator.geolocation = { getCurrentPosition (geolocationSuccess, [geolocationError], [geolocationOptions]), int watchPosition (geolocationSuccess, [geolocationError], [geolocationOptions]), clearWatch (watchId)}
    27. 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 inmeters, heading: Direction of travel, specified in degreesclockwise relative to the true north, speed: Current ground speed of the device, in m/s }, timestamp: The timestamp when the reading was taken.}
    28. 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. 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 wouldlike to receive the best possible results, timeout: The maximum timeout in milliseconds of the call togeolocation.getCurrentPosition or geolocation.watchPosition, maximumAge: Dont accept a cached position older than thespecified time in milliseconds}
    30. 30. Geolocation Example// onSuccess Callbackvar 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: + new Date(position.timestamp) + n);};// onError Callback receives a PositionError objectfunction onError(error) { alert(code: + error.code + n + message: + error.message + n);}navigator.geolocation.getCurrentPosition(onSuccess, onError);
    31. 31. Camera (1) Provides access to the device camera  Resides in window.navigator and has just one method to work with: navigator.camera.getPicture(onSuccess, onFail, [Settings]);  Takes a photo using the camera or retrieves a photo from the devices album. The image is returned as a base64 encoded String or as the URI of the image file.
    32. 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. 33. Camera Examplenavigator.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. 34. Contacts (1) Provides access to the device contacts DB. Initialized as navigator.contacts.navigator.contacts = { create(properties), find(contactFields, contactSuccess, [contactError], [contactFindOptions])} Use the create() method to create a new contact object and then the save() method in it to save it to the phone databasecontact = navigator.contacts.create({"displayName": "Test User"}); Use the find() method to filter contacts and get the fields you need.
    35. 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 ContactField array of all phone numbers, emails: A ContactField array of all email addresses, addresses: A ContactAddress array of all addresses, ims: A ContactField array of all the contacts IM addresses, organizations: A ContactOrganization array of all organizations, birthday: The birthday of the contact, note: A note about the contact, photos: A ContactField array of the contacts photos, categories: A ContactField array of all user categories, urls: A ContactField array of contact’s web pages}
    36. 36. Contacts (3) There are also three methods in the Contact object :{ 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} 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.)}
    37. 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. 38. Contacts (6) ContactOrganization field consists of the following properties: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.} And finally ContactField has only two:ContactField = { type: The field type (example: ‘office), value: The value of the field (such as a phone numberor email address)}
    39. 39. Contacts (7) contactError receives an error object with one of the following error codes: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 contactFields is a requred parameter of the find() method, specified as an array of strings:["name", "phoneNumbers", "emails"] contactFindOptions is optional, but you can specify additional find settings with it:ContactFindOptions = { filter: Search string to filter contacts - default "", multiple: Should return multiple results – default false}
    40. 40. Contacts Examplefunction onSuccess(contacts) { alert(Found + contacts.length + contacts.);};function onError(contactError) { alert(onError!);};// find all contacts with Bob in any name fieldvar options = new ContactFindOptions(); options.filter="Bob‚, fields = ["displayName", "name"];navigator.contacts.find(fields, onSuccess, onError, options);
    41. 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. 42. PhoneGap Hardware Manipulation курсове и уроци по програмиране, уеб дизайн – безплатно BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране – Телерик академия форум програмиране, форум уеб дизайн уроци по програмиране и уеб дизайн за ученици ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET http://mobiledevcourse.telerik.com програмиране за деца – безплатни курсове и уроци ASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC безплатен SEO курс - оптимизация за търсачки алго академия – състезателно програмиране, състезаниякурсове и уроци по програмиране, книги – безплатно от Наков курс мобилни приложения с iPhone, Android, WP7, PhoneGap уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop Дончо Минков - сайт за програмиране free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране безплатен курс "Качествен програмен код" безплатен курс "Разработка на софтуер в cloud среда" C# курс, програмиране, безплатно
    43. 43. 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.
    44. 44. Free Trainings @ Telerik Academy Cross-Platform Mobile Development http://mobiledevcourse.telerik.com Telerik Software Academy  academy.telerik.com Telerik Academy @ Facebook  facebook.com/TelerikAcademy Telerik Software Academy Forums  forums.academy.telerik.com