introduction phonegap

Post on 02-Jul-2015

214 Views

Category:

Mobile

1 Downloads

Preview:

Click to see full reader

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

Introduction to PhoneGap

Rakesh Kumar Jha

M.Tech, MBA

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

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.

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.

Introduction to PhoneGap

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

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.

Introduction of Phonegap

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

Introduction of Phonegap

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

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.

PhoneGap Architecture

PhoneGap Architecture

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

PhoneGap Architecture

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

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

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

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.

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

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.

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.

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.

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)

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.

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="contact@tutorialspoint.com"> Tutorials Point </author>

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>

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>

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

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.

config.xml

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

<description> My First Web App </description>

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>

Event Types

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

Event Types

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

– batterycritical

– batterylow

– batterystatus

Event Types

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

– online

– offline

deviceready

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

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

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>

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

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>

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.

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>

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

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>

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

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>

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.

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>

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

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>

Getting Information from the Device

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)

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

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

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>

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>

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>

Using Notifications

Notification

• Visual, audible, and tactile device notifications

Notification

• Methods

– notification.alert

– notification.confirm

– notification.beep

– notification.vibrate

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

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

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.

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

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>

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

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>

notification.beep

• The device will play a beep sound.

navigator.notification.beep(times);

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>

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>

notification.vibrate

• Vibrates the device for the specified amount of time.

navigator.notification.vibrate(milliseconds)

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>

Accelerometer

Accelerometer

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

Accelerometer

• Methods

– accelerometer.getCurrentAcceleration

– accelerometer.watchAcceleration

– accelerometer.clearWatch

Accelerometer

• Arguments

– accelerometerSuccess

– accelerometerError

– accelerometerOptions

Accelerometer Permissions

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

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

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>

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)

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>

Media

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

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)

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;

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

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

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.

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

top related