accessing the device native apis kamen bundev telerik academy academy.telerik.com senior front-end...

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

Upload: dwight-gray

Post on 15-Jan-2016

219 views

Category:

Documents


0 download

TRANSCRIPT

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

PhoneGap Hardware Manipulation

Accessing the device native APIs

Kamen Bundev

Telerik Academyacademy.telerik.com

Senior Front-End Developerhttp://www.telerik.com

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

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

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

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.

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

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}

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

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

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

Connection API

The Connection API

Available under navigator.network Holds a single property – type Can be used to determine the

network/internet connectivity

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

Connection API (2)

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

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

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

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

Events 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

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

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

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

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

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

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

}

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

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 }

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

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 device's charger is plugged or unplugged

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

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

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

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)

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

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

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

Compass (2) The Compass object dwells under 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.}

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

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

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}

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

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

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

Compass Example

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

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

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

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

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

}

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

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

}

var options = { frequency: 3000 }; // Update every 3 seconds,watchID = navigator.accelerometer.watchAcceleration

(onSuccess, onError,options);

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

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 location can be inaccurate due to the current device positioning method.

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

Geolocation (2) The Geolocation API resides in the

window.navigator object.

navigator.geolocation = {getCurrentPosition (geolocationSuccess,

[geolocationError], [geolocationOptions]),

int watchPosition (geolocationSuccess,[geolocationError],[geolocationOptions]),

clearWatch (watchId)}

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

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.

}

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

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

}

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

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}

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

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

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

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

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

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

};

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

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

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

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

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

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

}

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

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

}

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

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

}

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

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

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

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"]

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

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

Contacts Example

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

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

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

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

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.