Download presentation
Presentation is loading. Please wait.
Published byDwight Gray Modified over 9 years ago
1
Accessing the device native APIs Kamen Bundev Telerik Academy academy.telerik.com Senior Front-End Developer http://www.telerik.com
2
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
Holds the description of the device hardware and software, the application is currently running on: { name = Device Model Name, name = Device Model Name, phonegap = PhoneGap version, phonegap = PhoneGap version, platform = returns the OS platform name, platform = returns the OS platform name, uuid = returns an unique device ID, uuid = returns an unique device ID, version = returns OS version version = returns OS version}
5
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]), alert(message, alertCallback, [title], [buttonName]), confirm(message, confirmCallback, [title], [buttonLabels]), confirm(message, confirmCallback, [title], [buttonLabels]), vibrate(milliseconds), vibrate(milliseconds), beep(times) } beep(times) }
6
The Connection API Available under navigator.network Holds a single property – type Can be used to determine the network/internet connectivity
7
When the application is initialized, network.connection.type can 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
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(); connection.typeConnection connection.typeConnection
9
There are numerous events fired at different stages of PhoneGap's 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
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, onDeviceReady, false); false); function onDeviceReady() { // Fill out the PhoneGap version $("#phonegap_version").text(device.phonegap); }
11
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
document.addEventListener("pause", onPause, false); document.addEventListener("resume", onResume, false); function onPause() { navigator.compass.clearWatch(compassId); } function onResume() { compassId = navigator.compass compassId = navigator.compass.watchHeading(.watchHeading( function (heading) { // do something });}
13
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 // Handle the online event} function onOffline() { // Handle the offline event // Handle the offline event}
14
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
All these events receive an object with two properties, when fired - level (battery level from 0-100) and isPlugged - boolean. window.addEventListener("batterystatus", onBatteryStatus, onBatteryStatus, false); false); function onBatteryStatus(info) { console.log("Level: " + info.level + " isPlugged: " + info.isPlugged); }
16
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
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
The Compass object dwells under the window.navigator object and sports the following properties and methods: navigator.compass = { getCurrentHeading(compassSuccess, [compassError], [compassOptions]), getCurrentHeading(compassSuccess, [compassError], [compassOptions]), int watchHeading(compassSuccess, [compassError], [compassOptions]), int watchHeading(compassSuccess, [compassError], [compassOptions]), clearWatch(watchId), clearWatch(watchId), int watchHeadingFilter(compassSuccess, [compassError], [compassOptions]), // Only on iOS. int watchHeadingFilter(compassSuccess, [compassError], [compassOptions]), // Only on iOS. clearWatchFilter(watchId) // Only on iOS. clearWatchFilter(watchId) // Only on iOS.}
19
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 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
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
function 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 seconds var watchID = navigator.compass.watchHeading(onSuccess, onError,options);
22
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
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
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!');} var options = { frequency: 3000 }; // Update every 3 seconds, watchID = navigator.accelerometer.watchAcceleration (onSuccess, onError, options);
25
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 location can be inaccurate due to the current device positioning method.
26
The Geolocation API resides in the window.navigator object. navigator.geolocation = { getCurrentPosition (geolocationSuccess, [geolocationError],[geolocationOptions]), int watchPosition (geolocationSuccess, [geolocationError],[geolocationOptions]), clearWatch (watchId) }
27
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
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
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
// onSuccess Callback 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: ' + new Date(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);
31
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
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
navigator.camera.getPicture(onSuccess,onFail,{ quality: 50, destinationType: Camera.DestinationType.FILE_URI Camera.DestinationType.FILE_URI}); function onSuccess(imageURI) { var image = document.getElementById('myImage'); var image = document.getElementById('myImage'); image.src = imageURI; image.src = imageURI;} function onFail(message) { alert('Failed because: ' + message); alert('Failed because: ' + message);}
34
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
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 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 ContactField array of the contact's photos, categories: A ContactField array of all user categories, urls: A ContactField array of contact’s web pages }
36
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
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, postalCode: The zip code or postal code, country: The country name }
38
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
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"] ContactFindOptions = { filter: Search string to filter contacts - default "", multiple: Should return multiple results – default false } 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
40
function onSuccess(contacts) { alert('Found ' + contacts.length + ' contacts.'); alert('Found ' + contacts.length + ' contacts.');}; function onError(contactError) { alert('onError!'); 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
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 http://docs.phonegap.com Read about the following APIs: Storage Capture Media File
42
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.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.