





















































In this article, you will develop, build, and deploy your first Apache Cordova application from scratch. The application you will develop is a Sound Recorder utility that you can use to record your voice or any sound and play it back. In this chapter, you will learn about the following topics:
(For more resources related to this topic, see here.)
In order to create, develop, build, and test a Cordova application, you first need to use the Cordova CLI. Using this, you can create new Apache Cordova project(s), build them on mobile platforms such as iOS, Android, Windows Phone, and so on, and run them on real devices or within emulators. Note that in this chapter, we will focus on deploying our Sound Recorder application in Android devices only.
In the next chapter, we will learn how to deploy our Sound Recorder application in iOS and Windows Phone devices.
Before installing Apache Cordova CLI, you need to make sure that you install the following software:
After installing Node.js, you should be able to run Node.js or node package manager (npm) from the command line. In order to install Apache Cordova using npm, run the following command (you can omit sudo if you are working in a Windows environment):
> sudo npm install -g cordova
It's worth mentioning that npm is the official package manager for Node.js and it is written completely in JavaScript. npm is a tool that allows users to install Node.js modules, which are available in the npm registry.
The sudo command allows a privileged Unix user to execute a command as the super user, or as any other user, according to the sudoers file. The sudo command, by default, requires you to authenticate with a password. Once you are authenticated, you can use the command without a password, by default, for 5 minutes.
After successfully installing Apache Cordova (Version 3.4.0), you should be able to execute Apache Cordova commands from the command line, for example, the following command will show you the current installed version of Apache Cordova:
> cordova -version
In order to execute the Cordova commands without any problem, you also need to have Apache Ant installed and configured in your operating system.
You can download Apache Ant from http://ant.apache.org. The complete instructions on how to install Ant are mentioned at https://ant.apache.org/manual/install.html.
After installing Apache Cordova, we can start creating our Sound Recorder project by executing the following command:
> cordova create soundRecorder com.jsmobile.soundrecorder SoundRecorder
After successfully executing this command, you will find a message similar to the following one (note that the location path will be different on your machine):
Creating a new cordova project with name "SoundRecorder" and id "com.jsmobile.soundrecorder" at location "/Users/xyz/projects/soundRecorder"
If we analyze the cordova create command, we will find that its first parameter represents the path of your project. In this command, a soundRecorder directory will be generated for your project under the directory from which the cordova create command is executed. The second and third parameters are optional. The second parameter, com.jsmobile.soundrecorder, provides your project's namespace (it should be noted that in Android projects, this namespace will be translated to a Java package with this name), and the last parameter, SoundRecorder, provides the application's display text. You can edit both these values in the config.xml configuration file later, which will be illustrated soon.
The following screenshot shows our SoundRecorder project's generated artifacts:
As shown in the preceding screenshot, the generated Apache Cordova project contains the following main directories:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.jsmobile.soundrecorder" version="0.0.1"
>
<name>SoundRecorder</name>
<description>
A sample Apache Cordova application that responds to the deviceready event.
</description>
<author email="dev@cordova.apache.org" href="http://cordova.io">
Apache Cordova Team
</author>
<content src="index.html" />
<access origin="*" />
</widget>
Specifying the <access> element's origin to * is fine during application development, but it is considered a bad practice in production due to security concerns. Note that before moving your application to production, you should review its whitelist and declare its access to specific network domains and subdomains.
<preference name="Fullscreen" value="true" />
<preference name="HideKeyboardFormAccessoryBar" value="true"/>
If we look in the www directory, we will find that it contains the following three files:
The following code snippet includes the most important part of the index.html page:
<div class="app">
<h1>Apache Cordova</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
The index.html page has a single div "app", which contains a child div "deviceready". The "deviceready" div has two paragraph elements, the "event listening" and "event received" paragraphs. The "event received" paragraph is initially hidden as indicated by index.css:
.event.received {
background-color:#4B946A;
display:none;
}
In the index.html page, there are two main JavaScript-included files, as follows:
Finally, the index.html page calls the initialize() method of the app object. Let's see the details of the app object in index.js:
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement =
parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
The initialize() method calls the bindEvents() method, which adds an event listener for the 'deviceready' event. When the device is ready, the onDeviceReady() method is called, and this in turn calls the receivedEvent() method of the app object.
In the receivedEvent() method, the "event listening" paragraph is hidden and the "event received" paragraph is shown to the user. This is to display the Device is Ready message to the user once Apache Cordova is fully loaded.
It is important to note that you must not call any Apache Cordova API before the 'deviceready' event fires. This is because the 'deviceready' event fires only once Apache Cordova is fully loaded.
Now you have an Apache Cordova project that has common cross-platform code,
so we need to generate a platform-specific code in order to deploy our code on a
real device. To generate Android platform code, you need to add the Android platform as follows:
> cd soundRecorder
> cordova platform add android
In order to add any platform, you need to execute the cordova platform command from the application directory. Note that in order to execute the cordova platform command without problems, you need to perform the following instructions:
After executing the cordova platform add command, you will find a new subdirectory Android added under the soundRecorder/platforms directory, which is added by Android. In order to build the project, use the following command:
> cordova build
Finally, you can run and test the generated Android project in the emulator by executing the following command:
> cordova emulate android
You might see the ERROR: No emulator images (avds) found message flash if no Android AVDs are available in your operating system. So, make sure you create one!
The following screenshot shows our Sound Recorder application's initial screen:
It is recommended that you make your code changes in the root www directory,
and not in the platforms/android/assets/www directory (especially if you are targeting multiple platforms) as the platforms directory will be overridden every time you execute the cordova build command, unless you are willing to use Apache Cordova CLI to initialize the project for a single platform only.
After generating the initial application code, it's time to understand what to do next.
The following screenshot shows our Sound Recorder page:
When the user clicks on the Record Sound button, they will be able to record their voices; they can stop recording their voices by clicking on the Stop Recording button. You can see this in the following screenshot:
As shown in the following screenshot, when the user clicks on the Playback button, the recorded voice will be played back:
In order to implement this functionality using Apache Cordova, we need to add the following plugins using the indicated commands, which should be executed from the application directory:
> cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-media.git
> cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git
> cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-file.git
In order to apply these plugins to our Apache Cordova project, we need to run the cordova build command again from the project directory, as follows:
> cordova build
Now we are done with the preparation of our Sound Recorder application.
Before moving to the code details, let's see the hierarchy of our Sound Recorder application, as shown in the following screenshot:
The application's www directory contains the following directories:
Finally, the index.html file contains the application's single page whose functionality was illustrated earlier in this section.
It is important to note that Apache Cordova does not require you to use a JavaScript mobile User Interface (UI) framework. However, it is recommended that you use a JavaScript mobile UI framework in addition to Apache Cordova. This is in order to facilitate building the application UI and speed up the application development process.
Let's see the details of the index.html page of our Sound Recorder application.
The following code snippet shows the included files in the page:
<link rel="stylesheet" type="text/css" href="css/app.css" />
<link rel="stylesheet" href="jqueryMobile/jquery.mobile-1.4.0.min.css">
<script src="jqueryMobile/jquery-1.10.2.min.js"></script>
<script src="jqueryMobile/jquery.mobile-1.4.0.min.js"></script>
...
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/app.js"></script>
In the preceding code, the following files are included:
It is important to know that you can download the jQuery mobile framework files from http://jquerymobile.com/download/.
The following code snippet shows the HTML content of our application's single page, whose id is "main":
<div data-role="page" id="main">
<div data-role="header">
<h1>Sound Recorder</h1>
</div>
<div data-role="content">
<div data-role="fieldcontain">
<h1>Welcome to the Sound Recorder Application</h1>
<p>Click 'Record Sound' button in order to start
recording. You will be able to see
the playback button once the sound recording
finishes.<br/><br/></p>
<input type="hidden" id="location"/>
<div class="center-wrapper">
<input type="button" id="recordSound" data-
icon="audio" value="Record Sound" class="center-button" data-
inline="true"/>
<input type="button" id="playSound" data-
icon="refresh" value="Playback" class="center-button" data-
inline="true"/><br/>
</div>
<div data-role="popup" id="recordSoundDialog" data-
dismissible="false" style="width:250px">
<div data-role="header">
<h1>Recording</h1>
</div>
<div data-role="content">
<div class="center-wrapper">
<div id="soundDuration"></div>
<input type="button" id="stopRecordingSound" value="Stop Recording"
class="center-button" data-
inline="true"/>
</div>
</div>
</div>
</div>
</div>
<div data-role="footer" data-position="fixed">
<h1>Powered by Apache Cordova</h1>
</div>
</div>
Looking at the preceding code, our Sound Recording page ("main") is defined by setting a div's data-role attribute to "page". It has a header defined by setting a div's data-role to "header". It has content defined by setting a div's data-role to "content", which contains the recording and playback buttons.
The content also contains a "recordSoundDialog" pop up, which is defined by setting a div's data-role to "popup". The "recordSoundDialog" pop up has a header and content. The pop-up content displays the recorded audio duration in the "soundDuration" div, and it has a "stopRecordingSound" button that stops recording the sound.
Finally, the page has a footer defined by setting a div's data-role to "footer", which contains a statement about the application.
Now, it's time to learn how we can define event handlers on the the page HTML elements and use the Apache Cordova API inside our defined event handlers to implement the application's functionality.
The following code snippet shows the page initialization code:
(function() {
$(document).on("pageinit", "#main", function(e) {
e.preventDefault();
function onDeviceReady() {
$("#recordSound").on("tap", function(e) {
// Action is defined here ...
});
$("#recordSoundDialog").on("popupafterclose",
function(event, ui) {
// Action is defined here ...
});
$("#stopRecordingSound").on("tap", function(e) {
// Action is defined here ...
});
$("#playSound").on("tap", function(e) {
// Action is defined here ...
});
}
$(document).on('deviceready', onDeviceReady);
initPage();
});
// Code is omitted here for simplicity
function initPage() {
$("#playSound").closest('.ui-btn').hide();
}
})();
In jQuery mobile, the "pageinit" event is called once during page initialization. In this event, the event handlers are defined and the page is initialized. Note that all of the event handlers are defined after the 'deviceready' event fires. The event handlers are defined for the following:
In initPage(), the "playSound" button is hidden as no voice has been recorded yet. As you noticed, in order to hide an element in jQuery mobile, you just need to call its hide() method. We can now see the details of each event handler; the next code snippet shows the "recordSound" tap event handler:
var recInterval;
$("#recordSound").on("tap", function(e) {
e.preventDefault();
var recordingCallback = {};
recordingCallback.recordSuccess = handleRecordSuccess;
recordingCallback.recordError = handleRecordError;
startRecordingSound(recordingCallback);
var recTime = 0;
$("#soundDuration").html("Duration: " + recTime + " seconds");
$("#recordSoundDialog").popup("open");
recInterval = setInterval(function() {
recTime = recTime + 1;
$("#soundDuration").html("Duration: " + recTime + " seconds");
}, 1000);
});
The following actions are performed in the "recordSound" tap event handler:
The following code snippet shows the startRecordingSound(recordingCallback), stopRecordingSound(), and requestApplicationDirectory(callback) functions:
var BASE_DIRECTORY = "CS_Recorder";
var recordingMedia;
function startRecordingSound(recordingCallback) {
var recordVoice = function(dirPath) {
var basePath = "";
if (dirPath) {
basePath = dirPath + "/";
}
var mediaFilePath = basePath + (new Date()).getTime() +
".wav";
var recordingSuccess = function() {
recordingCallback.recordSuccess(mediaFilePath);
};
recordingMedia = new Media(mediaFilePath,
recordingSuccess, recordingCallback.recordError);
// Record audio
recordingMedia.startRecord();
};
if (device.platform === "Android") {
var callback = {};
callback.requestSuccess = recordVoice;
callback.requestError = recordingCallback.recordError;
requestApplicationDirectory(callback);
} else {
recordVoice();
}
}
function stopRecordingSound() {
recordingMedia.stopRecord();
recordingMedia.release();
}
function requestApplicationDirectory(callback) {
var directoryReady = function (dirEntry) {
callback.requestSuccess(dirEntry.toURL());
};
var fileSystemReady = function(fileSystem) {
fileSystem.root.getDirectory(BASE_DIRECTORY, {create:
true}, directoryReady);
};
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
fileSystemReady, callback.requestError);
}
The next section illustrates the preceding code snippet.
In order to record the audio files using Apache Cordova, we need to create a Media object, as follows:
recordingMedia = new Media(src, mediaSuccess, mediaError);
The Media object constructor has the following parameters:
In order to start recording an audio file, a call to the startRecord() method of the Media object must be performed. When the recording is over, a call to stopRecord() of the Media object method must be performed.
In startRecordingSound(recordingCallback), the function gets the current device platform by using device.platform, as follows:
Note that using the native Windows Phone 8 API (Window.Storage), you can read and write files in an SD card with some restrictions. However, until the moment you cannot do this using Apache Cordova; hopefully this capability will soon be supported by Cordova (http://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn611857.aspx).
function handleRecordSuccess(currentFilePath) {
$("#location").val(currentFilePath);
$("#playSound").closest('.ui-btn').show();
}
$("#recordSoundDialog").on("popupafterclose", function(event, ui) {
clearInterval(recInterval);
stopRecordingSound();
});
$("#stopRecordingSound").on("tap", function(e) {
$("#recordSoundDialog").popup("close");
});
function stopRecordingSound(recordingCallback) {
recordingMedia.stopRecord();
recordingMedia.release();
}
In the "stopRecordingSound" tapping event handler, it closes the open "recordSoundDialog" pop up. Generally, if "recordSoundDialog" is closed by the "stopRecordingSound" button's tapping action or by pressing special device keys, such as the back button in Android devices, then the recording timer stops as a result of calling clearInterval(recInterval), and then it calls the stopRecordingSound() function to stop recording the sound.
The stopRecordingSound() function calls the Media object's stopRecord() method, and then releases it by calling the Media object's release() method. The following code snippet shows the "playSound" tap event handler:
var audioMedia;
var recordingMedia;
$("#playSound").on("tap", function(e) {
e.preventDefault();
var playCallback = {};
playCallback.playSuccess = handlePlaySuccess;
playCallback.playError = handlePlayError;
playSound($("#location").val(), playCallback);
});
function playSound(filePath, playCallback) {
if (filePath) {
cleanUpResources();
audioMedia = new Media(filePath, playCallback.playSuccess,
playCallback.playError);
// Play audio
audioMedia.play();
}
}
function cleanUpResources() {
if (audioMedia) {
audioMedia.stop();
audioMedia.release();
audioMedia = null;
}
if (recordingMedia) {
recordingMedia.stop();
recordingMedia.release();
recordingMedia = null;
}
}
In the "playSound" tap event handler, it calls the playSound(filePath, playCallback) function by passing the audio file location, which is stored in the "location" hidden field and playCallback.
The playSound(filePath, playCallback) function uses the Media object's play() method to play back the saved audio file after releasing used Media objects. Note that this is a requirement to avoid running out of system audio resources.
Now, after developing our application code, we can start building our application using the following cordova build command:
> cordova build
In order to run the application in your Android mobile or tablet, just make sure you enable USB debugging in your Android device. Then, plug your Android device into your development machine and execute the following command from the application directory:
> cordova run android
Congratulations! After running this command, you will see the Sound Recorder application deployed in your Android device; you can now start testing it on your real device.
In this article, you developed your first Apache Cordova application. You now know how to use the Apache Cordova Device API at a basic level. You also know how to use the Media and File APIs along with jQuery mobile to develop the Sound Recorder application. You now understand how to use Apache Cordova CLI in order to manage your Cordova mobile application. In addition, you know how to create a Cordova project, add a new platform (in our case, Android), build your own Cordova mobile application, and deploy your Cordova mobile application to the emulator, and most importantly, to a real device!
To learn more, refer to these books:
Further resources on this subject: