introduction phonegap

86
Introduction to PhoneGap Rakesh Kumar Jha M.Tech, MBA

Upload: rakesh-jha

Post on 02-Jul-2015

212 views

Category:

Mobile


1 download

DESCRIPTION

Introduction to PhoneGap Background Setting up the environment for Android Handling Events Working With The Device, The Network, And Notifications Getting Information from the Device Determining the Connection Type Using Notifications Using Alerts Using Confirmation Dialogs Using Beeps Using Vibrations Accelerometer Using the Acceleration Object Using Accelerometer Methods Media The Media Object Using Media Methods Camera Using The Camera Object Using The Getpicture Method Using Camera Options Geolocation Position, PositionError, Coord Geolocation Methods Geolocation Options Deployment using Phonegap (Android) Hands-on exercises Storage Available options Db object localStorage Files Filessystem File read & write Handling errors Contacts Creating contacts Finding contacts Handling errors Capture Video Audio Handling errors Hands-on exercises

TRANSCRIPT

Page 1: Introduction phonegap

Introduction to PhoneGap

Rakesh Kumar Jha

M.Tech, MBA

Page 2: Introduction phonegap

Introduction to PhoneGap Background Setting up the environment for Android Handling Events

Working With The Device, The Network, And Notifications Getting Information from the Device Determining the Connection Type Using Notifications Using Alerts Using Confirmation Dialogs Using Beeps Using Vibrations

Accelerometer Using the Acceleration Object Using Accelerometer Methods

Media The Media Object Using Media Methods

Camera Using The Camera Object Using The Getpicture Method Using Camera Options

Geolocation Position, PositionError, Coord Geolocation Methods Geolocation Options

Deployment using Phonegap (Android) Hands-on exercises

Page 3: Introduction phonegap

Introduction to PhoneGap

• To develop apps using PhoneGap, the developer does not require to have knowledge of mobile programming language but only web-development languages like, HTML, CSS, and JScript.

Page 4: Introduction phonegap

Introduction to PhoneGap

• To develop apps using PhoneGap, the developer does not require to have knowledge of mobile programming language but only web-development languages like, HTML, CSS, and JScript.

Page 5: Introduction phonegap

Introduction to PhoneGap

• PhoneGap produces apps for all popular mobile OS platforms such as iOS, Android, BlackBerry, and Windows Mobile OS etc

Page 6: Introduction phonegap

Prerequisites

• It is mandatory that you have knowledge of HTML, CSS and JScript to create website that you might want to put on App.

• No other programming language is required to use PhoneGap.

Page 7: Introduction phonegap

Introduction of Phonegap

• Mobile, handhelds and easy-to-carry devices have started a new revolution in software engineering.

Page 8: Introduction phonegap

Introduction of Phonegap

• These small but efficient devices are capable to run applications created with high-end programming languages.

Page 9: Introduction phonegap

PhoneGap Architecture

• The architecture of a mobile device is similar to that of a computer system.

• It has custom built hardware, firmware, and operating systems.

Page 10: Introduction phonegap

PhoneGap Architecture

Page 11: Introduction phonegap

PhoneGap Architecture

• These three items are mostly proprietary and are engineered, developed, and assembled under one flagship organization.

Page 12: Introduction phonegap

PhoneGap Architecture

• Apps (Application Software) are developed both by flagship organization and developers from outside the organization.

Page 13: Introduction phonegap

PhoneGap Architecture

• A number of well-recognized mobile operating systems are available in the market in both proprietary and open-source categories. Most widely used mobile operating systems are:

– Android

– IOS

– BlackBerry

– Windows

Page 14: Introduction phonegap
Page 15: Introduction phonegap

PhoneGap

• PhoneGap may be seen as a solution to all problems mentioned above.

• PhoneGap is a framework that makes the developers develop their apps using standard web APIs for all major mobile operating systems.

• It is open-source and free

Page 16: Introduction phonegap

PhoneGap

• Developers only need to know web development using HTML, CSS and JavaScript.

• PhoneGap takes care of rest of the work, such as look and feel of the app and portability among various mobile OS.

Page 17: Introduction phonegap

PhoneGap

Page 18: Introduction phonegap

PhoneGap

• Using PhoneGap, one can create apps for all major mobile OSl like Apple iOS, Android, BlackBerry, Windows etc.

• This does not require the developer to have expertise over any of the above mentioned platforms neither the developer is required to know programming to code the app from scratch

Page 19: Introduction phonegap

PhoneGap

• PhoneGap allows its users to upload the data contents on website and it automatically converts it to various App files.

• In this tutorial, we shall see how to create app for apple, android, and windows platform online and without using any offline tool.

Page 20: Introduction phonegap

PhoneGap

• Though PhoneGap supports offline creation of apps using cordova command line interface and Github repository mechanism but we shall concentrate on minimum effort procedure.

Page 21: Introduction phonegap

PhoneGap

• We assume that you are well versed with web technologies and have your web application ready to be shipped as an app.

• Because PhoneGap supports only HTML, CSS and JavaScript, it is mandatory that the application should be created using these technologies only.

Page 22: Introduction phonegap

PhoneGap

• From developers perspective, an app should have the following items included in its package:

– Configuration files

– Icons for app

– Information or content (built using web-technologies)

Page 23: Introduction phonegap

Configuration

• Our web app will need only one configuration file that should be adequate to configure all its necessary settings.

• Its name is config.xml.

• This file contains all the necessary information required to compile the app.

Page 24: Introduction phonegap

config.xml

<?xml version="1.0" encoding="UTF-8"?> <widget xmlns = "http://www.w3.org/ns/widgets" xmlns:gap = "http://phonegap.com/ns/1.0" id = "com.tutorialspoint.onlineviewer" version = "1.0"> <name>Tutorials Point</name> <description> Tutorials Point Online Viewer </description> <author href="http://tutorialspoint.com" email="[email protected]"> Tutorials Point </author>

Page 25: Introduction phonegap

config.xml

<preference name="permissions" value="none"/> <icon src="res/icon/android/drawable-ldpi/tp_icon.png" gap:platform="android" gap:qualifier="ldpi" /> <icon src="res/icon/android/drawable-mdpi/tp_icon.png" gap:platform="android" gap:qualifier="mdpi" /> <icon src="res/icon/android/drawable-hdpi/tp_icon.png" gap:platform="android" gap:qualifier="hdpi" /> <icon src="res/icon/android/drawable-xhdpi/tp_icon.png" gap:platform="android" gap:qualifier="xhdpi" /> <icon src="res/icon/android/drawable-xxhdpi/tp_icon.png" gap:platform="android" gap:qualifier="xxhdpi" /> <icon src="res/icon/ios/Icon-72.png" gap:platform="ios" gap:qualifier=""/> <icon src="res/icon/ios/icon-57.png" gap:platform="ios" width="57" height="57" /> <icon src="res/icon/ios/icon-72.png" gap:platform="ios" width="72" height="72" /> <icon src="res/icon/ios/icon-57-2x.png" gap:platform="ios" width="114" height="114" /> <icon src="res/icon/ios/icon-72-2x.png" gap:platform="ios" width="144" height="144" /> </widget>

Page 26: Introduction phonegap

config.xml

<preference name="permissions" value="none"/> <icon src="res/icon/android/drawable-ldpi/tp_icon.png" gap:platform="android" gap:qualifier="ldpi" /> <icon src="res/icon/android/drawable-mdpi/tp_icon.png" gap:platform="android" gap:qualifier="mdpi" /> <icon src="res/icon/android/drawable-hdpi/tp_icon.png" gap:platform="android" gap:qualifier="hdpi" /> <icon src="res/icon/android/drawable-xhdpi/tp_icon.png" gap:platform="android" gap:qualifier="xhdpi" /> <icon src="res/icon/android/drawable-xxhdpi/tp_icon.png" gap:platform="android" gap:qualifier="xxhdpi" /> <icon src="res/icon/ios/Icon-72.png" gap:platform="ios" gap:qualifier=""/> <icon src="res/icon/ios/icon-57.png" gap:platform="ios" width="57" height="57" /> <icon src="res/icon/ios/icon-72.png" gap:platform="ios" width="72" height="72" /> <icon src="res/icon/ios/icon-57-2x.png" gap:platform="ios" width="114" height="114" /> <icon src="res/icon/ios/icon-72-2x.png" gap:platform="ios" width="144" height="144" /> </widget>

Page 27: Introduction phonegap

config.xml

• All configuration contents are wrapped in <widget> tag. Brief description of these is as follows:

<widget id = ”app_id”>

• id is your reserved app-id on various app stores. It is in reverse-domain name style i.e. com.hp.phonegap.tutorial etc.

<widget version = "x.y.z">

Page 28: Introduction phonegap

config.xml

<name> App Name</name>

• This is name of app, which will be displayed below app icon on mobile screen. Your app can be searched using this name.

Page 29: Introduction phonegap

config.xml

• This is a brief description of what is the app about, and what it is.

<description> My First Web App </description>

Page 30: Introduction phonegap

config.xml

• This field contains name of the creator or programmer, generally set to the name of organization which is launching this app.

<author> Author_Name </author>

Page 31: Introduction phonegap

Event Types

• deviceready • pause • resume • backbutton • menubutton • searchbutton • startcallbutton • endcallbutton • volumedownbutton • volumeupbutton

Page 32: Introduction phonegap

Event Types

• Events added by org.apache.cordova.battery-status

– batterycritical

– batterylow

– batterystatus

Page 33: Introduction phonegap

Event Types

• Events added by org.apache.cordova.network-information

– online

– offline

Page 34: Introduction phonegap

deviceready

document.addEventListener("deviceready", yourCallbackFunction, false);

document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // Now safe to use device APIs }

Page 35: Introduction phonegap

deviceready

<!DOCTYPE html> <html> <head> <title>Device Ready Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // device APIs are available // function onDeviceReady() { // Now safe to use device APIs } </script> </head> <body onload="onLoad()"> </body> </html>

Page 36: Introduction phonegap

pause

document.addEventListener("pause", yourCallbackFunction, false);

• The pause event fires when the native platform puts the application into the background, typically when the user switches to a different application.

• Applications typically should use document.addEventListener to attach an event listener once the deviceready event fires

Page 37: Introduction phonegap

pause

<!DOCTYPE html> <html> <head> <title>Pause Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // device APIs are available // function onDeviceReady() { document.addEventListener("pause", onPause, false); } // Handle the pause event // function onPause() { } </script> </head> <body onload="onLoad()"> </body> </html>

Page 38: Introduction phonegap

resume

document.addEventListener("resume", yourCallbackFunction, false);

• The resume event fires when the native platform pulls the application out from the background.

• Applications typically should use document.addEventListener to attach an event listener once the deviceready event fires.

Page 39: Introduction phonegap

resume

<!DOCTYPE html> <html> <head> <title>Resume Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // device APIs are available // function onDeviceReady() { document.addEventListener("resume", onResume, false); } // Handle the resume event // function onResume() { } </script> </head> <body onload="onLoad()"> </body> </html>

Page 40: Introduction phonegap

backbutton

document.addEventListener("backbutton", yourCallbackFunction, false);

• To override the default back-button behavior, register an event listener for the backbutton event, typically by calling document.addEventListener once you receive the deviceready event.

• It is no longer necessary to call any other method to override the back-button behavior

Page 41: Introduction phonegap

backbutton

<!DOCTYPE html> <html> <head> <title>Back Button Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // device APIs are available // function onDeviceReady() { // Register the event listener document.addEventListener("backbutton", onBackKeyDown, false); } // Handle the back button // function onBackKeyDown() { } </script> </head> <body onload="onLoad()"> </body> </html>

Page 42: Introduction phonegap

menubutton

document.addEventListener("menubutton", yourCallbackFunction, false);

• Applying an event handler overrides the default menu button behavior.

• Applications typically should use document.addEventListener to attach an event listener once the deviceready event fires

Page 43: Introduction phonegap

menubutton

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Menu Button Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // device APIs are available // function onDeviceReady() { // Register the event listener document.addEventListener("menubutton", onMenuKeyDown, false); } // Handle the menu button // function onMenuKeyDown() { } </script> </head> <body onload="onLoad()"> </body> </html>

Page 44: Introduction phonegap

searchbutton

document.addEventListener("searchbutton", yourCallbackFunction, false);

• If you need to override the default search button behavior on Android you can register an event listener for the 'searchbutton' event.

• Applications typically should use document.addEventListener to attach an event listener once the deviceready event fires.

Page 45: Introduction phonegap

searchbutton

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Search Button Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // device APIs are available // function onDeviceReady() { // Register the event listener document.addEventListener("searchbutton", onSearchKeyDown, false); } // Handle the search button // function onSearchKeyDown() { } </script> </head> <body onload="onLoad()"> </body> </html>

Page 46: Introduction phonegap

startcallbutton

• If you need to override the default start call behavior you can register an event listener for the startcallbutton event.

• Applications typically should use document.addEventListener to attach an event listener once the deviceready event fires.

document.addEventListener("startcallbutton", yourCallbackFunction, false);

Page 47: Introduction phonegap

startcallbutton

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Start Call Button Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // device APIs are available // function onDeviceReady() { // Register the event listener document.addEventListener("startcallbutton", onStartCallKeyDown, false); } // Handle the start call button // function onStartCallKeyDown() { } </script> </head> <body onload="onLoad()"> </body> </html>

Page 48: Introduction phonegap

Getting Information from the Device

Page 49: Introduction phonegap

Getting Information from the Device

• Permission required –

– <plugin name="Device" value="org.apache.cordova.Device" /> (inside app/res/xml/plugins.xml)

– <uses-permission android:name="android.permission.READ_PHONE_STATE" /> (inside Menifest file)

Page 50: Introduction phonegap

Getting Information from the Device

$('#devicename').html(device.name); $('#devicephonegap').html(device.phonegap); $('#devicplatform').html(device.platform); $('#deviceuuid').html(device.uuid); $('#deviceversion').html(device.version);

Page 51: Introduction phonegap

Getting Information from the Device

<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="format-detection" content="telephone=no" /> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> <link rel="stylesheet" type="text/css" href="jquery.mobile-1.2.0.css" /> <script type="text/javascript" src="jquery-1.8.2.js"></script> <script type="text/javascript" src="jquery.mobile-1.2.0.js"></script> <script type="text/javascript"> $(document).on("pageinit", "#newpage", function () { $('#saveButton').click(function () { localStorage.setItem("name", $('#name').val()); }); }); var wID = navigator.accelerometer.watchAcceleration(onSucess, onerror, { frequency: 1000 }); function onSucess(a) { $('#aX').html(a.x); $('#aY').html(a.y); $('#aZ').html(a.z); $('#aTime').html(a.timestamp); } function onError() { }

Page 52: Introduction phonegap

Getting Information from the Device

var phoneName = window.device.name; var phoneName = device.name; $('#devicename').html(device.name); $('#devicephonegap').html(device.phonegap); $('#devicplatform').html(device.platform); $('#deviceuuid').html(device.uuid); $('#deviceversion').html(device.version); $(document).on('pageshow', '#newpage', function () { var personName = localStorage.getItem("name"); if (personName.length > 0) { $('#name').val(personName); } }); </script> <title>Hello World 2</title> </head> <body> <div id="home" data-role="page"> <div data-role="header"> <h1>Home Page2</h1> </div> <div data-role="content"> hello Phone Gap and JQuery Mobile! <a href="#newpage" data-role="button">new page</a> <br> <p id="devicename"> </p> <p id="devicephonegap"> </p> <p id="deviceplatform"> </p> <p id="deviceuuid"> </p> <p id="deviceversion"> </p> <p id="ax"> </p> <p id="ay"> </p> <p id="az"> </p> <p id="aTime"> </p> </div>

Page 53: Introduction phonegap

Getting Information from the Device

<div id="newpage" data-role="page"> <div data-role="header"> <a href="#home" data-icon="delete">Cancel</a> <h1>New Page</h1> <a href=#home" data-icon="save">save</a> </div> <div data-role="content"> <label for="name">what is your name?</label> <input id="name" type="text" name="name" value="" /> <a id="saveButton" href="" data-role="button">Save</a> </div> <div data-role="footer" data-position="fixed"> <h4> footer</h4> </div> </div> <div id="dialogpage" data-role="page"> <div data-role="header"> <h1>Dialog</h1> </div> <div data-role="content"> this is a dialog </div> </div> <script type="text/javascript" src="cordova-2.1.0.js"></script> <script type="text/javascript" src="js/index.js"></script> <script type="text/javascript"> app.initialize(); </script> </body> </html>

Page 54: Introduction phonegap

Device Info

<!DOCTYPE html> <html> <head> <title>Device Properties Example</title> <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for Cordova to load // document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready // function onDeviceReady() { var element = document.getElementById('deviceProperties'); element.innerHTML = 'Device Name: ' + device.name + '<br />' + 'Device Cordova: ' + device.cordova + '<br />' + 'Device Platform: ' + device.platform + '<br />' + 'Device UUID: ' + device.uuid + '<br />' + 'Device Version: ' + device.version + '<br />'; } </script> </head> <body> <p id="deviceProperties">Loading device properties...</p> </body> </html>

Page 55: Introduction phonegap

Using Notifications

Page 56: Introduction phonegap

Notification

• Visual, audible, and tactile device notifications

Page 57: Introduction phonegap

Notification

• Methods

– notification.alert

– notification.confirm

– notification.beep

– notification.vibrate

Page 58: Introduction phonegap

Notification Permissions

• app/res/xml/plugins.xml <plugin name="Notification" value="org.apache.cordova.Notification"/>

• app/AndroidManifest.xml <uses-permission android:name="android.permission.VIBRATE" />

Page 59: Introduction phonegap

notification.alert

• Shows a custom alert or dialog box. navigator.notification.alert(message, alertCallback, [title], [buttonName])

– message: Dialog message (String)

– alertCallback: Callback to invoke when alert dialog is dismissed. (Function)

– title: Dialog title (String) (Optional, Default: "Alert")

– buttonName: Button name (String) (Optional, Default: "OK")

Page 60: Introduction phonegap

notification.alert

• Most Cordova implementations use a native dialog box for this feature.

• However, some platforms simply use the browser's alertfunction, which is typically less customizable.

Page 61: Introduction phonegap

notification.alert

// Android / BlackBerry WebWorks (OS 5.0 and higher) / iPhone / Tizen // function alertDismissed() { // do something } navigator.notification.alert( 'You are the winner!', // message alertDismissed, // callback 'Game Over', // title 'Done' // buttonName );

Page 62: Introduction phonegap

notification.alert <!DOCTYPE html>

<html> <head> <title>Notification Example</title>

<script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script> <script type="text/javascript" charset="utf-8">

// Wait for Cordova to load //

document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready

// function onDeviceReady() { // Empty

} // alert dialog dismissed

function alertDismissed() { // do something }

// Show a custom alert //

function showAlert() { navigator.notification.alert( 'You are the winner!', // message

alertDismissed, // callback 'Game Over', // title 'Done' // buttonName

); }

</script> </head> <body>

<p><a href="#" onclick="showAlert(); return false;">Show Alert</a></p> </body> </html>

Page 63: Introduction phonegap

notification.confirm

• Shows a customizable confirmation dialog box. navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])

– message: Dialog message (String)

– confirmCallback: - Callback to invoke with index of button pressed (1, 2 or 3). (Function)

– title: Dialog title (String) (Optional, Default: "Confirm")

– buttonLabels: Comma separated string with button labels (String) (Optional, Default: "OK,Cancel")

Page 64: Introduction phonegap

notification.confirm <!DOCTYPE html> <html> <head> <title>Notification Example</title> <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for Cordova to load // document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready // function onDeviceReady() { // Empty } // process the confirmation dialog result function onConfirm(buttonIndex) { alert('You selected button ' + buttonIndex); } // Show a custom confirmation dialog // function showConfirm() { navigator.notification.confirm( 'You are the winner!', // message onConfirm, // callback to invoke with index of button pressed 'Game Over', // title 'Restart,Exit' // buttonLabels ); } </script> </head> <body> <p><a href="#" onclick="showConfirm(); return false;">Show Confirm</a></p> </body> </html>

Page 65: Introduction phonegap

notification.beep

• The device will play a beep sound.

navigator.notification.beep(times);

Page 66: Introduction phonegap

notification.beep <html> <head> <title>Notification Example</title> <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for Cordova to load // document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready // function onDeviceReady() { // Empty } // Show a custom alert // function showAlert() { navigator.notification.alert( 'You are the winner!', // message 'Game Over', // title 'Done' // buttonName ); } // Beep three times // function playBeep() { navigator.notification.beep(3); } // Vibrate for 2 seconds // function vibrate() { navigator.notification.vibrate(2000); } </script> </head> <body> <p><a href="#" onclick="showAlert(); return false;">Show Alert</a></p> <p><a href="#" onclick="playBeep(); return false;">Play Beep</a></p> <p><a href="#" onclick="vibrate(); return false;">Vibrate</a></p> </body> </html>

Page 67: Introduction phonegap

notification.beep <html> <head> <title>Notification Example</title> <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for Cordova to load // document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready // function onDeviceReady() { // Empty } // Show a custom alert // function showAlert() { navigator.notification.alert( 'You are the winner!', // message 'Game Over', // title 'Done' // buttonName ); } // Beep three times // function playBeep() { navigator.notification.beep(3); } // Vibrate for 2 seconds // function vibrate() { navigator.notification.vibrate(2000); } </script> </head> <body> <p><a href="#" onclick="showAlert(); return false;">Show Alert</a></p> <p><a href="#" onclick="playBeep(); return false;">Play Beep</a></p> <p><a href="#" onclick="vibrate(); return false;">Vibrate</a></p> </body> </html>

Page 68: Introduction phonegap

notification.vibrate

• Vibrates the device for the specified amount of time.

navigator.notification.vibrate(milliseconds)

Page 69: Introduction phonegap

notification.vibrate <html> <head> <title>Notification Example</title> <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for Cordova to load // document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready // function onDeviceReady() { // Empty } // Show a custom alert // function showAlert() { navigator.notification.alert( 'You are the winner!', // message 'Game Over', // title 'Done' // buttonName ); } // Beep three times // function playBeep() { navigator.notification.beep(3); } // Vibrate for 2 seconds // function vibrate() { navigator.notification.vibrate(2000); } </script> </head> <body> <p><a href="#" onclick="showAlert(); return false;">Show Alert</a></p> <p><a href="#" onclick="playBeep(); return false;">Play Beep</a></p> <p><a href="#" onclick="vibrate(); return false;">Vibrate</a></p> </body> </html>

Page 70: Introduction phonegap

Accelerometer

Page 71: Introduction phonegap

Accelerometer

• Captures device motion in the x, y, and z direction.

Page 72: Introduction phonegap

Accelerometer

• Methods

– accelerometer.getCurrentAcceleration

– accelerometer.watchAcceleration

– accelerometer.clearWatch

Page 73: Introduction phonegap

Accelerometer

• Arguments

– accelerometerSuccess

– accelerometerError

– accelerometerOptions

Page 74: Introduction phonegap

Accelerometer Permissions

• app/res/xml/plugins.xml <plugin name="Accelerometer" value="org.apache.cordova.AccelListener" />

Page 75: Introduction phonegap

accelerometer.getCurrentAcceleration

• Get the current acceleration along the x, y, and z axis.

navigator.accelerometer.getCurrentAcceleration(accelerometerSuccess, accelerometerError);

• The accelerometer is a motion sensor that detects the change (delta) in movement relative to the current device orientation.

• The accelerometer can detect 3D movement along the x, y, and z axis.

• The acceleration is returned using the accelerometerSuccess callback function

Page 76: Introduction phonegap

accelerometer.getCurrentAcceleration

<!DOCTYPE html>

<html> <head> <title>Acceleration Example</title>

<script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script> <script type="text/javascript" charset="utf-8">

// Wait for Cordova to load //

document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready

// function onDeviceReady() { navigator.accelerometer.getCurrentAcceleration(onSuccess, onError);

} // onSuccess: Get a snapshot of the current acceleration

// function onSuccess(acceleration) { alert('Acceleration X: ' + acceleration.x + '\n' +

'Acceleration Y: ' + acceleration.y + '\n' + 'Acceleration Z: ' + acceleration.z + '\n' + 'Timestamp: ' + acceleration.timestamp + '\n');

} // onError: Failed to get the acceleration

// function onError() { alert('onError!');

} </script>

</head> <body> <h1>Example</h1>

<p>getCurrentAcceleration</p> </body> </html>

Page 77: Introduction phonegap

Acceleration

• Contains Accelerometer data captured at a specific point in time.

• Properties – x: Amount of acceleration on the x-axis. (in m/s^2)

(Number) – y: Amount of acceleration on the y-axis. (in m/s^2)

(Number) – z: Amount of acceleration on the z-axis. (in m/s^2)

(Number) – timestamp: Creation timestamp in milliseconds.

(DOMTimeStamp)

Page 78: Introduction phonegap

Acceleration <!DOCTYPE html> <html> <head> <title>Acceleration Example</title> <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for Cordova to load // document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready // function onDeviceReady() { navigator.accelerometer.getCurrentAcceleration(onSuccess, onError); } // onSuccess: Get a snapshot of the current acceleration // function onSuccess(acceleration) { alert('Acceleration X: ' + acceleration.x + '\n' + 'Acceleration Y: ' + acceleration.y + '\n' + 'Acceleration Z: ' + acceleration.z + '\n' + 'Timestamp: ' + acceleration.timestamp + '\n'); } // onError: Failed to get the acceleration // function onError() { alert('onError!'); } </script> </head> <body> <h1>Example</h1> <p>getCurrentAcceleration</p> </body> </html>

Page 79: Introduction phonegap

Media

Page 80: Introduction phonegap

Media

• The Media object provides the ability to record and play back audio files on a device.

var media = new Media(src, mediaSuccess, [mediaError], [mediaStatus]);

Page 81: Introduction phonegap

Media

• src: A URI containing the audio content. (DOMString)

• mediaSuccess: (Optional) The callback that is invoked after a Media object has completed the current play/record or stop action. (Function)

• mediaError: (Optional) The callback that is invoked if there was an error. (Function)

• mediaStatus: (Optional) The callback that is invoked to indicate status changes. (Function)

Page 82: Introduction phonegap

Media

Constants

• The following constants are reported as the only parameter to the mediaStatus callback function. – Media.MEDIA_NONE = 0;

– Media.MEDIA_STARTING = 1;

– Media.MEDIA_RUNNING = 2;

– Media.MEDIA_PAUSED = 3;

– Media.MEDIA_STOPPED = 4;

Page 83: Introduction phonegap

Media Permissions

• app/res/xml/plugins.xml <plugin name="Media" value="org.apache.cordova.AudioHandler" />

• app/AndroidManifest.xml <uses-permission android:name="android.permission.RECORD_AUDIO" />

<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Page 84: Introduction phonegap

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"

"http://www.w3.org/TR/html4/strict.dtd"> <html> <head>

<title>Media Example</title> <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script>

<script type="text/javascript" charset="utf-8"> // Wait for Cordova to load

// document.addEventListener("deviceready", onDeviceReady, false);

// Cordova is ready // function onDeviceReady() {

playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); }

// Audio player // var my_media = null;

var mediaTimer = null; // Play audio

// function playAudio(src) { // Create Media object from src

my_media = new Media(src, onSuccess, onError); // Play audio

my_media.play(); // Update my_media position every second

if (mediaTimer == null) { mediaTimer = setInterval(function() { // get my_media position

my_media.getCurrentPosition( // success callback function(position) {

if (position > -1) { setAudioPosition((position) + " sec"); }

}, // error callback function(e) {

console.log("Error getting pos=" + e); setAudioPosition("Error: " + e); }

); }, 1000); }

} // Pause audio

// function pauseAudio() { if (my_media) {

my_media.pause(); } }

// Stop audio //

function stopAudio() { if (my_media) { my_media.stop();

} clearInterval(mediaTimer); mediaTimer = null;

} // onSuccess Callback

// function onSuccess() { console.log("playAudio():Audio Success");

} // onError Callback

// function onError(error) { alert('code: ' + error.code + '\n' +

'message: ' + error.message + '\n'); }

// Set audio position // function setAudioPosition(position) {

document.getElementById('audio_position').innerHTML = position; }

</script> </head> <body>

<a href="#" class="btn large" onclick="playAudio('http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3');">Play Audio</a> <a href="#" class="btn large" onclick="pauseAudio();">Pause Playing Audio</a> <a href="#" class="btn large" onclick="stopAudio();">Stop Playing Audio</a>

<p id="audio_position"></p> </body> </html>

Page 85: Introduction phonegap

media.getDuration

• Returns the duration of an audio file. media.getDuration();

• Description

• Function media.getDuration is a synchronous function that returns the duration of the audio file in seconds, if known. If the duration is unknown, a value of -1 is returned.

Page 86: Introduction phonegap

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"

"http://www.w3.org/TR/html4/strict.dtd"> <html> <head>

<title>Media Example</title> <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script>

<script type="text/javascript" charset="utf-8"> // Wait for Cordova to load

// document.addEventListener("deviceready", onDeviceReady, false);

// Cordova is ready // function onDeviceReady() {

playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); }

// Audio player // var my_media = null;

var mediaTimer = null; // Play audio

// function playAudio(src) { // Create Media object from src

my_media = new Media(src, onSuccess, onError); // Play audio

my_media.play(); // Update my_media position every second

if (mediaTimer == null) { mediaTimer = setInterval(function() { // get my_media position

my_media.getCurrentPosition( // success callback function(position) {

if (position > -1) { setAudioPosition((position) + " sec"); }

}, // error callback function(e) {

console.log("Error getting pos=" + e); setAudioPosition("Error: " + e); }

); }, 1000); }

} // Pause audio

// function pauseAudio() { if (my_media) {

my_media.pause(); } }

// Stop audio //

function stopAudio() { if (my_media) { my_media.stop();

} clearInterval(mediaTimer); mediaTimer = null;

} // onSuccess Callback

// function onSuccess() { console.log("playAudio():Audio Success");

} // onError Callback

// function onError(error) { alert('code: ' + error.code + '\n' +

'message: ' + error.message + '\n'); }

// Set audio position // function setAudioPosition(position) {

document.getElementById('audio_position').innerHTML = position; }

</script> </head> <body>

<a href="#" class="btn large" onclick="playAudio('http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3');">Play Audio</a> <a href="#" class="btn large" onclick="pauseAudio();">Pause Playing Audio</a> <a href="#" class="btn large" onclick="stopAudio();">Stop Playing Audio</a>

<p id="audio_position"></p> </body> </html>