Practicals Journal
Practicals Journal
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.
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.
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:
Run the following command to build the project for all platforms:
$ cordova build android
This is an event that fires when the user presses the volume up button.
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.
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:
Code:
Backbutton
The event fires when the user presses the back button.
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:
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
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
<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){
function onFail(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.
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
<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.
Although the object is attached to the global scoped navigator, it is not available until after the deviceready event.
function onDeviceReady() {
console.log(navigator.accelerometer);
}
Installation:
Methods:
• navigator.accelerometer.getCurrentAcceleration
• navigator.accelerometer.watchAcceleration
• navigator.accelerometer.clearWatch
navigator.accelerometer.getCurrentAcceleration
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
Code:
HTML
</div>
JAVASCRIPT
document.getElementById("getAcceleration").addEventListener("click", getAcceleration);
function getAcceleration() {
navigator.accelerometer.getCurrentAcceleration(accelerometerSuccess, accelerometerError);
function accelerometerSuccess(acceleration) {
};
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.
Although the object is attached to the global scoped navigator, it is not available until after the deviceready event.
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
JAVASCRIPT
document.getElementById("getOrientation").addEventListener("click", getOrientation);
screen.orientation.lock('landscape');
function getOrientation() {
navigator.compass.getCurrentHeading(compassSuccess, compassError);
function compassSuccess(heading) {
};
function compassError(error) {
};
Function notification.prompt displays a native dialog box that is more customizable than the browser's prompt
function
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:
Code:
HTML
<div style= "width: 100%; text-align: center; margin: auto; margin-top: 30%;">
</div>
JAVASCRIPT
document.getElementById('prompt').addEventListener('click',showPrompt);
var options = ["Display","Cancel"];
function showPrompt(){
navigator.notification.prompt(
promptCallback,
"Welcome User"
);
function promptCallback(results){
if(buttonIndex==1){
}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.
Although in the global scope, it is not available until after the deviceready event.
function onDeviceReady() {
console.log(cordova.file);
}
Installation:
cordova plugin add cordova-plugin-file
Code:
HTML
JAVASCRIPT
document.getElementById("createFile").addEventListener("click", createFile);
document.getElementById("removeFile").addEventListener("click", removeFile);
function createFile() {
function successCallback(fs) {
}, errorCallback);
function errorCallback(error) {
function removeFile() {
function successCallback(fs) {
fileEntry.remove(function() {
alert('File removed.');
}, errorCallback);
}, errorCallback);
function errorCallback(error) {
}
Practical No. 7
Installing and Using Media Plugin
This plugin provides the ability to record and play back audio files on a device.
Although in the global scope, it is not available until after the deviceready event.
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() {
function onSuccess() {
alert("playAudio Success");
function onError(error) {
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);
function networkInfo() {
function onOffline() {
function onOnline() {
}
Practical No. 9
Storing Data Locally in a Cordova App
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
JAVASCRIPT
document.getElementById("setLocalStorage").addEventListener("click", setLocalStorage);
document.getElementById("showLocalStorage").addEventListener("click", showLocalStorage);
document.getElementById("removeProject").addEventListener("click", removeProject);
function setLocalStorage() {
function showLocalStorage() {
function removeProject() {
localStorage.removeItem("Project");