0% found this document useful (0 votes)
52 views

Practicals Journal

This document provides information about the Cordova platform for building hybrid mobile applications using HTML, CSS and JavaScript. It defines Cordova as an open-source mobile development framework that allows developers to use standard web technologies like HTML5, CSS3 and JavaScript for cross-platform development instead of each mobile platform's native development language. Applications execute within wrappers targeted to each platform and rely on standards-compliant API bindings to access each device's sensors, data and network status. Key Cordova features include its Command Line Interface, core components, plugins and Apache license.

Uploaded by

Sakshi Khatate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Practicals Journal

This document provides information about the Cordova platform for building hybrid mobile applications using HTML, CSS and JavaScript. It defines Cordova as an open-source mobile development framework that allows developers to use standard web technologies like HTML5, CSS3 and JavaScript for cross-platform development instead of each mobile platform's native development language. Applications execute within wrappers targeted to each platform and rely on standards-compliant API bindings to access each device's sensors, data and network status. Key Cordova features include its Command Line Interface, core components, plugins and Apache license.

Uploaded by

Sakshi Khatate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

PRACTICAL 1

Cordova is a platform for building hybrid mobile applications using HTML, CSS and JavaScript.

"Apache Cordova is an open-source mobile development framework. It allows you to use standard
web technologies such as HTML5, CSS3, and JavaScript for cross platform development, avoiding each
mobile platform native development language. Applications execute within wrappers targeted to each
platform, and rely on standards-compliant API bindings to access each device's sensors, data, and
network status."

Cordova Features
Let us now understand the features of Cordova in brief.

Command Line Interface (Cordova CLI):


This tool can be used for starting projects, building processes for different platforms, installing plugins
and lot of other useful things that make the development process easier. You will learn how to use the
Command Line Interface in the subsequent chapters.

Cordova Core Components:


Cordova offers a set of core components that every mobile application needs. These components will be used for
creating base of the app so we can spend more time to implement our own logic.

Cordova Plugins:
Cordova offers API that will be used for implementing native mobile functions to our JavaScript app.

License:
Cordova is licensed under the Apache License, Version 2.0. Apache and the Apache feather logos are
trademarks of The Apache Software Foundation.

A: Creating and building simple “Hello World” App using Cordova.

Create the App:


Go to the directory where you maintain your source code, and create a cordova project:

$ cordova create hello com.example.hello MyApp

This creates the required directory structure for your cordova app. By default, the cordova create script generates a
skeletal web-based application whose home page is the project's www/index.html file.

Add Platforms:
All subsequent commands need to be run within the project's directory, or any subdirectories:

$ cd hello

Add the platforms that you want to target your app. We will add the 'ios' and 'android' platform and ensure they get
saved to config.xml and package.json:

$ cordova platform add android

Build the App:


By default, cordova create script generates a skeletal web-based application whose start page is the project's
www/index.html file. Any initialization should be specified as part of the deviceready event handler defined in
www/js/index.js.

Run the following command to build the project for all platforms:
$ cordova build android

Test the App:


SDKs for mobile platforms often come bundled with emulators that execute a device image, so that you can launch
the app from the home screen and see how it interacts with many platform features. Run a command such as the
following to rebuild the app and view it within a specific platform's emulator:

$ cordova emulate android

B: Adding and Using Buttons.


Volumeupbutton:

This is an event that fires when the user presses the volume up button.

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

If you need to override the default volume up behaviour you can register an event listener for the
'volumeupbutton' event.

Typically, you will want to attach an event listener with document.addEventListener once you receive
the Cordova 'deviceready' event.

Volumedownbutton:
This is an event that fires when the user presses the volume down button.

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

Details
If you need to override the default volume down behaviour you can register an event listener for the
'volumedownbutton' event.
Typically, you will want to attach an event listener with document.addEventListener once you receive
the Cordova 'deviceready' event.

Code:

document.addEventListener("volumeupbutton", callbackFunction, false);


function callbackFunction() {
alert('Volume Up Button is pressed!');
}

Code:

document.addEventListener("volumedownbutton", callbackFunction, false);


function callbackFunction() {
alert('Volume Down Button is pressed!');
}
PRACTICAL 2
Handling and Using Back Button

Backbutton

The event fires when the user presses the back button.

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

Details

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](events.deviceready.html) event. It is no longer necessary to call any other method to
override the back-button behavior.

Code:

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


function onBackKeyDown(e) {
e.preventDetault();
alert(“Back Button Pressed”);
}
Practical No. 3
A: Installing and Using Battery Plugin

This plugin provides an implementation of an old version of the Battery Status Events API. It adds the
following three events to the window object:

• batterystatus
• batterycritical
• batterylow

Applications may use window.addEventListener to attach an event listener for any of the above events
after the deviceready event fires.

Installation:
cordova plugin add cordova-plugin-battery-status

Status object:
All events in this plugin return an object with the following properties:
• level: The battery charge percentage (0-100). (Number)
• isPlugged: A boolean that indicates whether the device is plugged in. (Boolean)

batterystatus event:
Fires when the battery charge percentage changes by at least 1 percent, or when the device is plugged
in or unplugged. Returns an object containing battery status.

Code:
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(status) {
alert("Level: " + status.level + " isPlugged: " + status.isPlugged); }
B: Installing and Using Camera Plugin

This plugin defines a global navigator.camera object, which provides an API for taking pictures and for choosing images
from the system's image library.
Although the object is attached to the global scoped navigator, it is not available until after the deviceready event.

Installation:
cordova plugin add cordova-plugin-camera

camera.getPicture(successCallback, errorCallback, options)

Takes a photo using the camera, or retrieves a photo from the device's image gallery. The image is passed to the
success callback as a Base64-encoded String, or as the URI for the image file.

The camera.getPicture function opens the device's default camera application that allows users to snap pictures by
default - this behavior occurs, when Camera.sourceType equals Camera.PictureSourceType.CAMERA. Once the user
snaps the photo, the camera application closes and the application is restored.

If Camera.sourceType is Camera.PictureSourceType.PHOTOLIBRARY or
Camera.PictureSourceType.SAVEDPHOTOALBUM, then a dialog displays that allows users to select an existing image.

camera.onError : (function)
Callback function that provides an error message.

camera.onSuccess : (function)
Callback function that provides the image data.
camera.CameraOptions : (Object)
Optional parameters to customize the camera settings.

Code:

HTML

<div style ="text-align: center; margin-top: 20px;">

<button id = "cameraApp">Camera</button>

</div>

<img src="" id="myImage" style="border:2px solid; width: 200px; height: 300px; Left: 50%; Top: 50%; position: fixed;
transform: translate(-50%,-50%);">

JAVASCRIPT

document.getElementById('cameraApp').addEventListener('click',cameraApp);

function cameraApp(){

navigator.camera.getPicture(onSuccess,onFail,{

quality:100,

saveToPhotoAlbum:true,

destinationType:Camera.DestinationType.DATA_URL

});

function onSuccess(imageData){

var image = document.getElementById('myImage');

image.src = "data:image/jepg;base64," + imageData;

function onFail(message){

alert('Failed beacause: ' + message);

}
Practical No. 4
A: Installing and Using Device Plugin

This plugin defines a global device object, which describes the device's hardware and software. Although the object
is in the global scope, it is not available until after the deviceready event.

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

function onDeviceReady() {
console.log(device.cordova);
}

Installation:
cordova plugin add cordova-plugin-device

Properties:
• device.model
The device.model returns the name of the device's model or product. The value is set by the device
manufacturer and may be different across versions of the same product.
• device.platform
Get the device's operating system name.
• device.uuid
Get the device's Universally Unique Identifier (UUID).
• device.version
Get the operating system version.
• device.manufacturer
Get the device's manufacturer.
• device.isVirtual
whether the device is running on a simulator.
• device.serial
Get the device hardware serial number (SERIAL).

Code:

HTML

<h2 style="text-align: center;">Device Info</h2>

<div>

<table>

<tr>

<td>Version</td>

<td><p id ="version"></p></td>

</tr>

<tr>

<td>Device Model</td>

<td><p id ="model"></p></td>

</tr>

<tr>
<td>Platform</td>

<td><p id ="platform"></p></td>

</tr>

<tr>

<td>UUID</td>

<td><p id ="uuid"></p></td>

</tr>

<tr>

<td>Andrion Version</td>

<td><p id ="androidVersion"></p></td>

</tr>

<tr>

<td>Manufacturer</td>

<td><p id ="manufacturer"></p></td>

</tr>

<tr>

<td>isVirtual</td>

<td><p id ="isvirtual"></p></td>

</tr>

<tr>

<td>Serial Number</td>

<td><p id ="serialNo"></p></td>

</tr>

</div>

JAVASCRIPT

document.getElementById("version").innerHTML = device.cordova;

document.getElementById("platform").innerHTML = device.platform;

document.getElementById("model").innerHTML = device.model;

document.getElementById("uuid").innerHTML = device.uuid;

document.getElementById("androidVersion").innerHTML = device.version;

document.getElementById("manufacturer").innerHTML = device.manufacturer;

document.getElementById("isvirtual").innerHTML = device.isvirtual;

document.getElementById("serialNo").innerHTML = device.serial;
B: Installing and Using Accelerometer Plugin

This plugin provides access to the device's accelerometer. The accelerometer is a motion sensor that detects the
change (delta) in movement relative to the current device orientation, in three dimensions along the x, y, and z axis.

Access is via a global navigator.accelerometer object.

Although the object is attached to the global scoped navigator, it is not available until after the deviceready event.

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

function onDeviceReady() {
console.log(navigator.accelerometer);
}

Installation:

cordova plugin add cordova-plugin-device-motion

Methods:
• navigator.accelerometer.getCurrentAcceleration
• navigator.accelerometer.watchAcceleration
• navigator.accelerometer.clearWatch

navigator.accelerometer.getCurrentAcceleration

Get the current acceleration along the x, y, and z axes.


These acceleration values are returned to the accelerometerSuccess callback function.
navigator.accelerometer.getCurrentAcceleration(accelerometerSuccess, accelerometerError);

navigator.accelerometer.watchAcceleration

Retrieves the device's current Acceleration at a regular interval, executing the accelerometerSuccess
callback function each time. Specify the interval in milliseconds via the acceleratorOptions object's
frequency parameter.
The returned watch ID references the accelerometer's watch interval, and can be used with
navigator.accelerometer.clearWatch to stop watching the accelerometer.

navigator.accelerometer.clearWatch

Stop watching the Acceleration referenced by the watchID parameter.


navigator.accelerometer.clearWatch(watchID);

Code:

HTML

<div style="width: 80%; margin: auto; text-align: center; margin-top: 30%;">

<h3>Using Accelerometer Plugin</h3></br></br>

<button id = "getAcceleration">GET ACCELERATION</button>

</div>

JAVASCRIPT

document.getElementById("getAcceleration").addEventListener("click", getAcceleration);
function getAcceleration() {

navigator.accelerometer.getCurrentAcceleration(accelerometerSuccess, accelerometerError);

function accelerometerSuccess(acceleration) {

alert('Acceleration X: ' + acceleration.x + '\n' +

'Acceleration Y: ' + acceleration.y + '\n' +

'Acceleration Z: ' + acceleration.z + '\n' +

'Timestamp: ' + acceleration.timestamp + '\n');

};

function accelerometerError() {

alert('onError!');

};

}
Practical No. 5
A: Install and Using Device Orientation plugin

This plugin provides access to the device's compass. The compass is a sensor that detects the direction or heading
that the device is pointed, typically from the top of the device. It measures the heading in degrees from 0 to 359.99,
where 0 is north.

Access is via a global navigator.compass object.

Although the object is attached to the global scoped navigator, it is not available until after the deviceready event.

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

function onDeviceReady() {
console.log(navigator.compass);
}

Installation:
cordova plugin add cordova-plugin-device-orientation
Methods:
• navigator.compass.getCurrentHeading
• navigator.compass.watchHeading
• navigator.compass.clearWatch

navigator.compass.getCurrentHeading:
Get the current compass heading. The compass heading is returned via a CompassHeading object using
the compassSuccess callback function.
navigator.compass.getCurrentHeading(compassSuccess, compassError);

navigator.compass.watchHeading:
Gets the device's current heading at a regular interval. Each time the heading is retrieved, the
headingSuccess callback function is executed.
The returned watch ID references the compass watch interval. The watch ID can be used with
navigator.compass.clearWatch to stop watching the navigator.compass.
var watchID = navigator.compass.watchHeading(compassSuccess, compassError, [compassOptions]);

navigator.compass.clearWatch:
Stop watching the compass referenced by the watch ID parameter.
navigator.compass.clearWatch(watchID);

Code:

HTML

<button id = "getOrientation">GET ORIENTATION</button>

JAVASCRIPT

document.getElementById("getOrientation").addEventListener("click", getOrientation);

screen.orientation.lock('landscape');

function getOrientation() {

navigator.compass.getCurrentHeading(compassSuccess, compassError);
function compassSuccess(heading) {

alert('Heading: ' + heading.magneticHeading);

};

function compassError(error) {

alert('CompassError: ' + error.code);

};

B: Create and Using Prompt Function

Function notification.prompt displays a native dialog box that is more customizable than the browser's prompt
function

navigator.notification.prompt(message, promptCallback, [title], [buttonLabels])

• message: Dialog message (String)


• promptCallback: - Callback to invoke when a button is pressed (Function)
• title: Dialog title (String) (Optional, Default: "Prompt")
• buttonLabels: Array of strings for the button labels (Array) (Optional, Default: ["OK","Cancel"])

promptCallback:

The promptCallback is called when the user has pressed one of the buttons on the prompt dialog box.

The callback takes the argument results which contains the following properties:

• buttonIndex: (Number), which is the index of the pressed button. It's important to note that the
index uses one-based indexing, so the value will be 1, 2, 3, etc.
• input1: (String), which is the text entered in the prompt dialog box.

Installation:

cordova plugin add cordova-plugin-dialogs

Code:

HTML

<div style= "width: 100%; text-align: center; margin: auto; margin-top: 30%;">

<h3>Using Prompt Function</h3></br></br>

<button id="prompt">Show Prompt</button>

</div>

JAVASCRIPT

document.getElementById('prompt').addEventListener('click',showPrompt);
var options = ["Display","Cancel"];

function showPrompt(){

navigator.notification.prompt(

"Please enter your name",

promptCallback,

"Welcome User"

);

function promptCallback(results){

var buttonIndex = results.buttonIndex;

var input1 = results.input1;

if(buttonIndex==1){

alert("Hello " + input1 + " welcome to College");

}else{

alert("cancelled");

}
Practical No. 6
Installing and Using File Plugin

This plugin implements a File API allowing read/write access to files residing on the device.

This plugin defines global cordova.file object.

Although in the global scope, it is not available until after the deviceready event.

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

function onDeviceReady() {
console.log(cordova.file);
}

Installation:
cordova plugin add cordova-plugin-file

Where to Store Files:


As of v1.2.0, URLs to important file-system directories are provided. Each URL is in the form file:///path/to/spot/,
and can be converted to a DirectoryEntry.

• cordova.file.applicationDirectory - Read-only directory where the application is installed.


• cordova.file.applicationStorageDirectory - Root directory of the application's sandbox.
• cordova.file.dataDirectory - Persistent and private data storage within the application's sandbox
using internal memory.
• cordova.file.cacheDirectory - Directory for cached data files or any files that your app can recreate
easily. The OS may delete these files when the device runs low on storage.
• cordova.file.externalApplicationStorageDirectory - Application space on external storage.
(Android).
• cordova.file.externalDataDirectory - Where to put app-specific data files on external storage.
(Android).
• cordova.file.externalRootDirectory - External storage (SD card) root.
• cordova.file.tempDirectory - Temp directory that the OS can clear at will.
• cordova.file.sharedDirectory - Files globally available to all applications

Code:

HTML

<button id = "createFile">CREATE FILE</button>

<button id = "removeFile">DELETE FILE</button>

JAVASCRIPT

document.getElementById("createFile").addEventListener("click", createFile);

document.getElementById("removeFile").addEventListener("click", removeFile);

function createFile() {

var type = window.TEMPORARY;

var size = 5*1024*1024;


window.requestFileSystem(type, size, successCallback, errorCallback)

function successCallback(fs) {

fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {

alert('File creation successfull!')

}, errorCallback);

function errorCallback(error) {

alert("ERROR: " + error.code)

function removeFile() {

var type = window.TEMPORARY;

var size = 5*1024*1024;

window.requestFileSystem(type, size, successCallback, errorCallback)

function successCallback(fs) {

fs.root.getFile('log.txt', {create: false}, function(fileEntry) {

fileEntry.remove(function() {

alert('File removed.');

}, errorCallback);

}, errorCallback);

function errorCallback(error) {

alert("ERROR: " + error.code)

}
Practical No. 7
Installing and Using Media Plugin

This plugin provides the ability to record and play back audio files on a device.

This plugin defines a global Media Constructor.

Although in the global scope, it is not available until after the deviceready event.

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

function onDeviceReady() {
console.log(Media);
}

Installation:
cordova plugin add cordova-plugin-media

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

Parameters:
• src: A URI containing the audio content. (DOMString)
• mediaSuccess: (Optional) The callback that executes after a Media object has completed the
current play, record, or stop action. (Function)
• mediaError: (Optional) The callback that executes if an error occurs. It takes an integer error
code. (Function)
• mediaStatus: (Optional) The callback that executes to indicate status changes. It takes a integer
status code. (Function)

Methods:
media.play: Start or resume playing an audio file.
media.pause: Pause playback of an audio file.
media.setVolume: Set the volume for audio playback.
media.stop: Stop playing an audio file.
media.getCurrentPosition: Returns the current position within an audio file.
media.getDuration: Returns the duration of an audio file.

Code:

HTML

<button id = "playAudio">PLAY</button>

<button id = "pauseAudio">PAUSE</button>

<button id = "stopAudio">STOP</button>

JAVASCRIPT

document.getElementById("playAudio").addEventListener("click", playAudio);

document.getElementById("pauseAudio").addEventListener("click", pauseAudio);

document.getElementById("stopAudio").addEventListener("click", stopAudio);
var myMedia = null;

function playAudio() {

var src = "/android_asset/www/audio/piano.mp3";

if(myMedia === null) {

myMedia = new Media(src, onSuccess, onError);

function onSuccess() {

alert("playAudio Success");

function onError(error) {

alert("playAudio Error: " + error.code);

myMedia.play();

function pauseAudio() {

if(myMedia) {

myMedia.pause();

function stopAudio() {

if(myMedia) {

myMedia.stop();

myMedia = null;

}
Practical No. 8
Installing and Using Network Information Plugin

This plugin provides information about the device's cellular and wifi connection, and whether the device has an
internet connection.

Installation:
cordova plugin add cordova-plugin-network-information

connection.type:

This property offers a fast way to determine the device's network connection state, and type of
connection.
• Connection.UNKNOWN
• Connection.ETHERNET
• Connection.WIFI
• Connection.CELL_2G
• Connection.CELL_3G
• Connection.CELL_4G
• Connection.CELL
• Connection.NONE

offline:
The event fires when an application goes offline, and the device is not connected to the Internet.
document.addEventListener("offline", yourCallbackFunction, false);

online:
This event fires when an application goes online, and the device becomes connected to the Internet.
document.addEventListener("online", yourCallbackFunction, false);

Code:

HTML

<button id = "networkInfo">INFO</button>

JAVASCRIPT

document.getElementById("networkInfo").addEventListener("click", networkInfo);

document.addEventListener("offline", onOffline, false);

document.addEventListener("online", onOnline, false);

function networkInfo() {

var networkState = navigator.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.CELL] = 'Cell generic connection';

states[Connection.NONE] = 'No network connection';

alert('Connection type: ' + states[networkState]);

function onOffline() {

alert('You are now offline!');

function onOnline() {

alert('You are now online!');

}
Practical No. 9
Storing Data Locally in a Cordova App

Several storage APIs are available for Cordova applications.

Each API offers advantages and disadvantages, which are summarized here. You should choose whichever best suits
your needs. You can also use several different approaches within a single application for different purposes

LocalStorage:
Local storage provides simple, synchronous key/value pair storage, and is supported by the underlying
WebView implementations on all Cordova platforms.

IndexedDB:
IndexedDB provides a simple and easy to understand data model, much like LocalStorage. But unlike

LocalStorage, you can create multiple databases, with multiple stores per database, and its
asynchronous API and search indexes provide performance benefits.

Code:

HTML

<button id = "setLocalStorage">SET LOCAL STORAGE</button>

<button id = "showLocalStorage">SHOW LOCAL STORAGE</button>

<button id = "removeProject">REMOVE PROJECT</button>

JAVASCRIPT

document.getElementById("setLocalStorage").addEventListener("click", setLocalStorage);

document.getElementById("showLocalStorage").addEventListener("click", showLocalStorage);

document.getElementById("removeProject").addEventListener("click", removeProject);

function setLocalStorage() {

localStorage.setItem("Name", "John ");

localStorage.setItem("Job", "Developer ");

localStorage.setItem("Project", "Cordova Project");

function showLocalStorage() {

alert(localStorage.getItem("Name") + localStorage.getItem("Job") + localStorage.getItem("Project"));

function removeProject() {

localStorage.removeItem("Project");

You might also like