Accessing Device Features
Upcoming SlideShare
Loading in...5
×
 

Accessing Device Features

on

  • 1,353 views

Mobile applications Development - Lecture 15 ...

Mobile applications Development - Lecture 15

Accessing Device Features:

Camera
Accelerometer
Contacts
Events

This presentation has been developed in the context of the Mobile Applications Development course at the Computer Science Department of the University of L’Aquila (Italy).

http://www.di.univaq.it/malavolta

Statistics

Views

Total Views
1,353
Views on SlideShare
1,353
Embed Views
0

Actions

Likes
1
Downloads
100
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Accessing Device Features Accessing Device Features Presentation Transcript

  • Accessing Device Features Ivano Malavolta ivano.malavolta@univaq.ithttp://www.di.univaq.it/malavolta
  • Roadmap• Media Capture• Camera• Contacts• Events• Accelerometer
  • Media Capture navigator.device.captureProvides access for capturing• Audio• Image• Videodirectly from the device
  • The Capture Object navigator.device.capturePropertiessupportedAudioModes The audio recording formats supported by the devicesupportedImageModes The recording image sizes and formats supported by the devicesupportedVideoModes The recording video resolutions and formats supported by the deviceThey all contain an array of ConfigurationData objects
  • ConfigurationDataIt is used to describe media capture modes supported by the deviceProperties:1. Type String Type: The string in lower case representing the media type – video/3gpp – audio/amr – video/quicktime – audio/wav – image/jpeg
  • ConfigurationData2. height integer height: The height of the image or video in pixels3. width integer width: The width of the image or video in pixelsIn the case of a sound clip, the value of these attributes is 0
  • Examplevar imageModes = navigator.device.capture.supportedImageModes;for each (var mode in imageModes) { console.log(mode.type); console.log(mode.height); console.log(mode.width);}
  • Capturing AudioIt is called on the capture objectStart the audio recorder application and return information about captured audio clip files
  • Capturing AudioIt starts an asynchronous operation to capture audio recordingsIt uses the devices default audio recording appThe operation allows the device user to capture multiple recordings in a single session
  • Capturing AudioWhen the capture operation is finished, it will invoke the CaptureCB callback with an array of MediaFile objectsIf the operation is terminated by the user before an audio clip is captured, the CaptureErrorCB callback will be invoked
  • Capture Audio OptionsEncapsulates audio capture configuration optionsProperties:• limit (not supported in iOS only 1 recording at a time) The maximum number of audio clips the device user can record in a single capture operation• Duration (not supported in Android unlimited) The maximum duration of an audio sound clip, in seconds audio/amr audio/wav• Mode (not supported in Android and iOS) The selected audio mode, it must match one of the elements in capture.supportedAudioModes
  • Audio Examplevar options = { limit: 2, duration: 5 };navigator.device.capture.captureAudio(win, fail, options);function win(mediaFiles) { var i; for (i=0; i<mediaFiles.length; i++) { console.log(mediaFiles[i]); }}function fail(error) { console.log(‘Error with code: + error.code);}
  • Capturing ImagesIt is called on the capture objectStart the camera application and return information about captured image file(s)
  • Capturing ImagesIt starts an asynchronous operation to capture imagesIt uses the device camera applicationThe operation allows the device user to capture multiple images in a single session
  • Capturing ImagesSimilarly to captureAudio...When the capture operation is finished, it will invoke the CaptureCB callback with an array of MediaFile objectsIf the operation is terminated by the user before any image is captured, the CaptureErrorCB callback will be invoked
  • Capture Image OptionsEncapsulates image capture configuration optionsProperties:• limit (not supported in iOS only 1 image at a time) The maximum number of images the device user can capture in a single capture operation• Mode (not supported in Android and iOS image/jpeg only) The selected image mode, it must match one of the elements in capture.supportedImageModes
  • Image Examplevar options = { limit: 3};navigator.device.capture.captureImage(win, fail, options);function win(mediaFiles) { It is very var i; similar to for (i=0; i<mediaFiles.length; i++) { the audio upload(mediaFiles[i]); } example!}function fail(error) { console.log(‘Error with code: + error.code);}
  • Recording VideosIt is called on the capture objectStart the video recorder application and return information about captured video clip file(s).
  • Recording VideosIt starts an asynchronous operation to record videosIt uses the device video recording applicationThe operation allows the device user to capture multiple recordings in a single session
  • Capturing VideosSimilarly to captureAudio...When the capture operation is finished, it will invoke the CaptureCB callback with an array of MediaFile objectsIf the operation is terminated by the user before any video is recorded, the CaptureErrorCB callback will be invoked
  • Capture Video OptionsEncapsulates video recording configuration optionsProperties:• limit (not supported in iOS only 1 video at a time) The maximum number of video clips the device user can record in a single capture operation• duration (not supported in Android and iOS unlimited) The maximum duration of a video clip, in seconds video/3gpp video/quicktime• mode (not supported in Android and iOS) The selected video recording mode, it must match one of the elements in capture.supportedVideoModes
  • Video Examplenavigator.device.capture.captureVideo(win, fail, {});function win(mediaFiles) { var i; It is very for (i=0; i<mediaFiles.length; i++) { similar to the upload(mediaFiles[i]); image & audio } examples!}function fail(error) { console.log(‘Error with code: + error.code);}
  • Media FilesA MediaFile encapsulates properties of a media capture fileName (String) The name of the file, without path informationfullPath (String) The full path of the file, including the nameType (String) The mime typelastModifiedDate (Date) The date and time that the file was last modifiedSize (Integer) The size of the file, in bytes
  • Capture ErrorsEncapsulates the error code resulting from a failed media capture operationIt contains a pre-defined error code pre- CaptureError.CAPTURE_INTERNAL_ERR CaptureError.CAPTURE_APPLICATION_BUSY CaptureError.CAPTURE_INVALID_ARGUMENT CaptureError.CAPTURE_NO_MEDIA_FILES CaptureError.CAPTURE_NOT__SUPPORTED
  • Roadmap• Media Capture• Camera• Contacts• Events• Accelerometer
  • CameraA dedicated API for capturing images from the device’s default camera applicationTakes a photo using the camera or retrieves a photo from the devices album
  • CameraThe result of a call to getPicture() can be:• a base64 encoded string, or• the URI of an image fileEncoding the image using Base64 has caused memory issues on some of these devices it is recommended to use the URI of the image file
  • Camera OptionsgetPicture() can be called with the following options
  • Camera Optionsquality (integer) Quality of saved image Range [0, 100]destinationType (Integer)
  • Camera OptionssourceType (integer)allowEdit (Boolean)Allow simple editing of image before selection
  • Camera OptionsencodingType (integer)targetWidth,targetWidth, targetHeight (Integer)Width/height in pixels to scale image
  • Camera OptionsmediaType (integer)correctOrientation (Boolean)Rotate the image to correct for the orientation of the device during capture
  • Camera OptionssaveToPhotoAlbum (Boolean)Save the image to the photo album on the device after capture Every platform has its own quirks, you better check them on the Cordova documentation
  • Camera Examplenavigator.camera.getPicture(win, fail,{ quality: 50, destinationType: destinationType.FILE_URI, pictureSource.PHOTOLIBRARY});function win(imageURI) { var element = $(“#block”); element.src(imageURI);}// fail function omitted here
  • Roadmap• Media Capture• Camera• Contacts• Events• Accelerometer
  • Contacts navigator.contactsIt is a global object that provides access to the device contacts DBYou can call 2 methods on navigator.contacts• contacts.create• contacts.find
  • Creating contacts navigator.contacts.create(properties)It is a synchronous function that returns a new Contact objectTo persist the Contact object to the device, you have to invoke the Contact.save method
  • Creating contacts navigator.contacts.create(properties)the properties parameter is a map of properties of the new Contact objectex.var contact = navigator.contacts.create({ "displayName": “Ivano“});
  • The Contact ObjectIt represents a user contactA contact can be created, saved or removed from the device contacts databaseThe contacts.find method is used for retrieving one or more Contacts from the device contacts database
  • Contact PropertiesIt contains all the properties that a contact can have Every platform has its own quirks, you better check them on the Cordova documentation
  • Contact MethodsA contact object provides the following methods• clone() Returns a new Contact object that is a deep copy of the calling object, its id property is null• remove(win, fail) Removes the contact from the device contacts database• save(win, fail) Saves a new contact to the device contacts database, or updates an existing contact if a contact with the same id already exists
  • Create Contact Examplevar contact = navigator.contacts.create({ "displayName": “Ivano“});var name = new ContactName();name.givenName = “Ivano“;name.familyName = “Malavolta“;contact.name = name;contact.birthday = new Date(“19 July 1983");contact.save(win, fail);function win(contact) { alert("Save Success");};function fail(contactError) { alert("Error = " + contactError.code);};
  • Finding contacts navigator.contacts.find( contactFields, contactSuccess, contactError, contactFindOptions );It is an asyncronous function that queries the device contacts database and returns an array of Contact objects
  • Find ParameterscontactFields,contactFields String Contact fields to be used as search qualifier. Only these fields will have values in the resulting Contact objectscontactSuccess Success callback function that is invoked with the array of contacts returned from the contacts databasecontactError [optional] Error callback functioncontactFindOptions [Optional] Search options to filter contacts
  • Contact FieldsSpecifies which fields should be included in the Contact objects resulting from a find operationvar fields = ["displayName", "name"]; // or [“*”]navigator.contacts.find(fields, win, fail);function win(contacts) { console.log(‘ok);};function fail(err) { console.log(err.code);};
  • Contact Find OptionsContains properties that can be used to filter the resultsPropertiesfilter (String) (Default: "")The search string used to find contactsA case-insensitive, partial value match is applied to each field specified in the contactFields parametermultiple (Boolean) (default: false)Determines if the find operation should return multiple contacts
  • Find Contact Examplevar options = new ContactFindOptions();options.filter = “Ivano";options.multiple = true;filter = ["displayName",“birthday"];navigator.contacts.find(filter, win, fail, options);function win(contacts) { for (var i=0; i<contacts.length; i++) { console.log(contacts[i].displayName); }};function fail(contactError) { alert("Error = " + contactError.code);};
  • ContactErrorIt is always returned to the fail callback when an error occurs 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
  • Roadmap• Media Capture• Camera• Contacts• Events• Accelerometer
  • EventsAn event is an action that can be detected by your Javascript codeIn traditional JS programs, any element of the page can have certain events – ontouchstart, onclick, ...
  • Listening to EventsTo use any event, you’ll want to use an event listenerdocument.addEventListener(EVENTNAME, onEvent, false);function onEvent() { // handle the event}EVENTNAME is the name of the event you want to listen toonEvent() is the callback function triggered every time the event is fired
  • Main Cordova Eventsother events are specific to Cordova applications• deviceready• pause, resume• online, offline• batterycritical, batterylow, batterystatus• backbutton, menubutton, searchbutton
  • devicereadyIt is the most important in event in a Cordova appCordova consists of two code bases:• native• JavaScriptOnce deviceready is fired, you know two things:1. The DOM has loaded2. the Cordova native API are loaded tooOnly at this point you can try to call Cordova APIs
  • App lifecycle EventsBased on two main events:pausefires when an application is put into the backgroundresumefires when a paused application is put back into the foreground
  • Connection Events When running in the WP emulator,Based on two main events: the connection.status of the device is always unknownonline the online event will NOT firefires when the applications network connection changes to being online (that is, it is connected to the Internet)offlinefires when the applications network connection changes to being offline (that is, no Internet connection available)
  • ConnectionIf you need to know the type of connection, you have to use the navigator.network.connection objectIt has a type property with one of the following values:Connection.UNKNOWNConnection.ETHERNETConnection.WIFIConnection.CELL_2GConnection.CELL_3GConnection.CELL_4GConnection.NONE
  • Battery EventsBased on three main events: this value isbatterycritical device-specificfires when the battery has reached the critical level thresholdbatterylowsimilar to batterycritical, but with a higher threeshold the battery status mustbatterystatus change of at least 1%fires a change in the battery status is detected
  • Battery EventsThe handler of a battery event is always called with an object that contains two properties:level (Integer) The percentage of battery (0-100)isPlugged (Boolean) Represents whether or not the device is plugged in or not
  • Android buttons EventsBased on three main events:backbuttonfires when the user presses the “back” buttonmenubuttonfires when the user presses the “menu” buttonsearchbuttonfires when the user presses the “search” button
  • Roadmap• Media Capture• Camera• Contacts• Events• Accelerometer
  • Accelerometer navigator.accelerometerIt is a global object that captures device motion in the x, y, and z directionYou can call 3 methods on it:• accelerometer.getCurrentAcceleration• accelerometer.watchAcceleration• accelerometer.clearWatch
  • getCurrentAccelerationIt gets the current acceleration along the x, y, and z axisgetCurrentAcceleration(win, fail);win callback function with an Acceleration parameterfail error callback
  • watchAccelerationIt gets the devices current acceleration at a regular intervalvar watchID = navigator.accelerometer.watchAcceleration(win, fail, [options]);win callback function with an Acceleration parameter, it is called at regular intervalsfail error callbackoptions the interval is specified in the frequency parameter
  • clearWatchStop watching the Acceleration referenced by the watch ID parameterclearWatch(watchID);watchID ID returned by accelerometer.watchAcceleration
  • AccelerationIt contains Accelerometer data captured at a specific point in time these values include the effect ofProperties gravity (9.81 m/s^2)x (Number) Amount of acceleration on the x-axis. (in m/s^2)y (Number) Amount of acceleration on the y-axis. (in m/s^2)z (Number) Amount of acceleration on the z-axis. (in m/s^2)timestamp (Timestamp) Creation timestamp in milliseconds
  • Examplevar options = { frequency: 3000 };var watchID = navigator.accelerometer.watchAcceleration(win, fail, options);function win(acc) { if((acc.x == 0) && (acc.y == 0) && (acc.z == 9,81)) { console.log(“I am on a table”); stop(); }}function fail() { console.log(“error”);}function stop() { if(watchID) { navigator.accelerometer.clearWatch(watchID); watchID = null; }}
  • Shake Detectionvar previousReading = {x: null, y: null, z: null};navigator.accelerometer.watchAcceleration(function (reading) { var changes = {}, bound = 3; if (previousReading.x !== null) { changes.x = Math.abs(previousReading.x, reading.x); changes.y = Math.abs(previousReading.y, reading.y); changes.z = Math.abs(previousReading.z, reading.z); } if (changes.x>bound && changes.y>bound && changes.z>bound) { console.log(‹shake detected); } previousReading = { x: reading.x, y: reading.y, z: reading.z }}, null, { frequency: 300 });
  • References