Accessing the device native APIs Kamen Bundev Telerik Academy academy.telerik.com Senior Front-End Developer

Slides:



Advertisements
Similar presentations
CIMCO Integration Software Products
Advertisements

TouchDevelop Chapter 5-7 Chapter 5 Audio Chapter 6 Camera, Graphics and Video Chapter 7 Sensors Mengfei Ren.
HTML 5 – GeoLocation and Maps. Geolocation API What is a ”geolocation”…? A geographical location, defined in terms of – Latitude (north/south) – Longitude.
The Android Activity Lifecycle. Slide 2 Introduction Working with the Android logging system Rotation and multiple layouts Understanding the Android activity.
UNDERSTANDING JAVA APIS FOR MOBILE DEVICES v0.01.
Tracking & Login Data persistence User tracking.
Mobile Application Development
Introduction CIS 136 Building Mobile Apps 1. What did we do Software review 2.
Microsoft Office Word 2013 Expert Microsoft Office Word 2013 Expert Courseware # 3251 Lesson 4: Working with Forms.
Phonegap Bridge – Battery API CIS 136 Building Mobile Apps 1.
Starter for 10 Unit 10: Flickr & YouTube Transform IT SFT10_Flickr_YouTube.
BY LINDA MOHAISEN MIKE ZIELINSKI The Tree Census Project.
CHAP 4. GEOLOCATION API.  You can request users to share their location and, if they agree, you can provide them with instructions on how to get to a.
UNIT 10 LINKS AND GEOLOCATION. OBJECTIVES  CO1 Describe various components of the Open Web Platform.  CO2 Create a website using HTML5.  CO3 Create.
What’s new for Windows 8 Devs Part 3 Lewis Benge Devices & Integration Team TBWA\Digital Arts Network DEV216.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
FireRMS SQL Audit, Archiving & Purging Presented by Laura Small FireRMS Quality Assurance.
Location-Based API 1. 2 Location-Based Services or LBS allow software to obtain the phone's current location. This includes location obtained from the.
Phonegap Bridge – Telephony CIS 136 Building Mobile Apps 1.
Lecture # 9 Hardware Sensor. Topics 2  SensorManger & Sensor  SensorEvent & SensorEventListener  Example Application.
Copyright© Jeffrey Jongko, Ateneo de Manila University Android.
INTRODUCTION TO HTML5 Geolocation. Display a Specific Location with Google Maps  You can use the Google Maps API to display a custom map on your own.
Campus Tour COMP 523 Final Presentation Justin, Paul, Florian.
CS378 - Mobile Computing Intents.
LiveCycle Data Services Introduction Part 2. Part 2? This is the second in our series on LiveCycle Data Services. If you missed our first presentation,
Introduction With TimeCard users can tag SharePoint events with information that converts them into time sheets. This way they can report.
GEOREMINDERS ANDROID APPLICATION BY: ADRIENNE KECK.
CS378 - Mobile Computing Intents. Allow us to use applications and components that are part of Android System – start activities – start services – deliver.
Phonegap Bridge – Compass API CIS 136 Building Mobile Apps 1.
Location. GPS Global Positioning System – At least 4 satellites typically used 3 required extra for error detection and altitude typically accurate within.
Sensors in android. App being more applicable Keeping track of your heart beat while jogging. Pointing the phone camera towards the night sky to know.
Phonegap Bridge – Device, Network, Console, Geolocation API’s CIS 136 Building Mobile Apps 1.
Multimedia Capture & storage. Introduction A rich set of API for recording of audio & video. A developer has two choices  launch the built-in app using.
Facebook for Beginners One Session Class. What will you learn today? What can you do on Facebook? Creating a profile Privacy Connecting with friends Sending.
EPICOLLECT Maggie Ortiz, EERI. EpiCollect Tutorial  This is a short tutorial prepared by EERI to walk you through creating an entry using EpiCollect.
Contract Invoice Guide
Center for Surveillance, Epidemiology, and Laboratory Services Division of Health Informatics and Surveillance José Aponte Public Health Advisor Companion.
Rich Internet Applications 9. HTML 5 and RIAs. HTML 5 Standard currently under development by W3C Aims to improve the language with support for the latest.
How to Recover Deleted Photos from Android Cell Phone? Android is keeping on improving their products and make sure to provide the best software service.
JavaScript, Sixth Edition
Phonegap Bridge –Geolocation and Google maps CIS 136 Building Mobile Apps 1.
Run the on your PC to start the firmware configuration process Run IP Config Tool.
Text2PTO: Modernizing Patent Application Filing A Proposal for Submitting Text Applications to the USPTO.
Phonegap Bridge – Device,Network, Vibration,Battery,Console CIS 136 Building Mobile Apps 1.
Accelerometer based motion gestures for mobile devices Presented by – Neel Parikh Advisor Committee members Dr. Chris Pollett Dr. Robert Chun Dr. Mark.
Phonegap Bridge – Storage CIS 136 Building Mobile Apps 1.
JavaScript, Sixth Edition
Mobile Applications (Android Programming)
Accessing the device native APIs
Architecture of Android
ANDROID AN OPEN HANDSET ALLIANCE PROJECT
CONTENT MANAGEMENT SYSTEM CSIR-NISCAIR, New Delhi
CIS 136 Building Mobile Apps
Windows Phone 7 advanced services
Geolocation using Google maps
Sensors, maps and fragments:
CIS 136 Building Mobile Apps
CIS 136 Building Mobile Apps
Phonegap Bridge Page Events, Physical Events, Device Events
iOS LifeRhythm Data Collection
CIS 136 Building Mobile Apps
CIS 136 Building Mobile Apps
Geolocation using Google maps
CIS 136 Building Mobile Apps
Phonegap Bridge Configuration file
CIS 136 Building Mobile Apps
CIS 136 Building Mobile Apps
Device,Network, Vibration, Console, Accelerometer
Device,Network, Vibration, Console, Accelerometer
Geolocation using Google maps
Presentation transcript:

Accessing the device native APIs Kamen Bundev Telerik Academy academy.telerik.com Senior Front-End Developer

 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

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

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

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

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

 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

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

 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

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

 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

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

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

 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

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

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

 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

 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.}

 compassSuccess receives one parameter - the current heading object, which consists of: CompassHeading = { magneticHeading: The heading in degrees from , trueHeading: The heading relative to the geographic North in degrees 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 }

 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. }

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

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

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

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

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

 The Geolocation API resides in the window.navigator object. navigator.geolocation = { getCurrentPosition (geolocationSuccess, [geolocationError],[geolocationOptions]), int watchPosition (geolocationSuccess, [geolocationError],[geolocationOptions]), clearWatch (watchId) }

 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. }

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

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

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

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

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

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

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

 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, s: A ContactField array of all 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 }

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

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

 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 address) }

 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", " s"] 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

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

 Today we covered part of the PhoneGap APIs, but there are still some left. As a homework, take a look at  Read about the following APIs:  Storage  Capture  Media  File

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