
Chapter 2. Developing Your First Cordova Application
In the previous chapter, you had a powerful introduction to Apache Cordova. In this chapter, 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:
- Generating your initial Apache Cordova project artifacts by utilizing the Apache Cordova Command-line Interface (CLI)
- Developing and building your mobile application from the initial Cordova generated code
- Deploying your developed mobile application to a real Android mobile device to see your application in action
An introduction to Cordova CLI
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.
Tip
In the next chapter, we will learn how to deploy our Sound Recorder application in iOS and Windows Phone devices.
Installing Apache Cordova
Before installing Apache Cordova CLI, you need to make sure that you install the following software:
- Target platform SDK: For Android, you can download its SDK from http://developer.android.com/sdk/index.html (for other platforms, you need to download and install their corresponding SDKs)
- Node.js: This is accessible at http://nodejs.org and can be downloaded and installed from http://nodejs.org/download/
Tip
If you want to know more about the details of configuring Android, iOS, and Windows Phone environments in your development machine, refer to Chapter 3, Apache Cordova Development Tools.
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.
Tip
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.
Generating our Sound Recorder's initial code
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:

The Sound Recorder's initial structure
As shown in the preceding screenshot, the generated Apache Cordova project contains the following main directories and files:
www
: This directory includes your application's HTML, JavaScript, and CSS code. You will also find the application's starting page (index.html
), along with various subdirectories, which are as follows:css
: This directory includes the default Apache Cordova application's CSS file (index.css
)js
: This directory includes the default Apache Cordova application's JavaScript file (index.js
)img
: This directory includes the default Apache Cordova application's logo file (logo.png
)
config.xml
: This file contains the application configuration. The following code snippet shows the initial code of theconfig.xml
file:<?xml version='1.0' encoding='utf-8'?> <widget id="com.jsmobile.soundrecorder" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"> <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>
As shown in the preceding
config.xml
file,config.xml
contains the following elements that are available on all the supported Apache Cordova platforms:- The
<widget>
element'sid
attribute represents the application's namespace identifier as specified in ourcordova create
command, and the<widget>
element'sversion
attribute represents its full version number in the form ofmajor.minor.patch
. - The
<name>
element specifies the application's name. - The
<description>
and<author>
elements specify the application's description and author, respectively. - The
<content>
element (which is optional) specifies the application's starting page that is placed directly under thewww
directory. The default value isindex.html
. - The
<access>
element(s) defines the set of external domains that the application is allowed to access. The default value is*
, which means that the application is allowed to access any external server(s).Tip
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.
There is another element that is not included in the default
config.xml
, and this is the<preference>
element. The<preference>
element(s) can be used to set the different preferences of the Cordova application and can work on all or a subset of the Apache Cordova-supported platforms. Take the example of the following code:<preference name="Fullscreen" value="true" /> <preference name="HideKeyboardFormAccessoryBar" value="true"/>
If the
Fullscreen
preference is set totrue
, it means that the application will be in fullscreen mode on all Cordova-supported platforms (by default, this option is set tofalse
). It is important to note that not all preferences work on all Cordova-supported platforms. Consider the following example:If the
HideKeyboardFormAccessoryBar
preference is set totrue
, then the additional helper toolbar, which appears above the device keyboard, will be hidden. This preference works only on iOS and BlackBerry platforms.- The
platforms
: This directory includes the application's supported platforms. After adding a new platform using Apache Cordova CLI, you will find a newly created directory that contains the platform-specific generated code under theplatforms
directory. Theplatforms
directory is initially empty because we have not added any platforms yet. We will add support to the Android platform in the next step.plugins
: This directory includes your application's used plugins. If you aren't already aware, a plugin is the mechanism to access the device's native functions in Apache Cordova. After adding a plugin (such as theMedia
plugin) to the project, you will find a newly created directory under theplugins
directory, which contains the plugin code. Note that we will add three plugins in our Sound Recorder application example.merges
: This directory can be used to override the common resources under thewww
directory. The files placed under themerges/[platform]
directory will override the matching files (or add new files) under thewww
directory for the specified platform (the[platform]
value can be iOS, Android, or any other valid supported platform).hooks
: This directory contains scripts that can be used to customize Apache Cordova commands. A hook is a piece of code that executes before and/or after the Apache Cordova command runs.
An insight into the www files
If we look in the www
directory, we will find that it contains the following three files:
index.html
: This file is placed under the application'swww
directory, and it contains the HTML content of the application pageindex.js
: This file is placed under thewww/js
directory, and it contains a simple JavaScript logic that we will illustrate soonindex.css
: This file is placed under thewww/css
directory, and it contains the style classes of the HTML elements
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:
cordova.js
: This file contains Apache Cordova JavaScript APIsindex.js
: This file contains the application's simple logic
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.
Tip
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:
- Have Apache Ant installed and configured in your operating system as described in the Installing Apache Cordova section
- Make sure that the path to your Android SDK platform tools and the tools directory are added to your operating system's
PATH
environment variable
After executing the cordova platform add
command, you will find a new subdirectory Android
added under the soundRecorder/platforms
directory. 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!
Tip
Refer to the Creating an Android virtual device section in Chapter 3, Apache Cordova Development Tools, to know how to create an Android AVD.
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.
Developing Sound Recorder application
After generating the initial application code, it's time to understand what to do next.
Sound Recorder functionality
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:

Sound Recorder preparation
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:
media
: This plugin is used to record and play back sound files:> cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-media.git
device
: This plugin is required to access the device information:> cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git
file
: This plugin is used to access the device's filesystem:> 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
Sound Recorder details
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:
css
: This directory contains the custom application CSS file(s)img
: This directory contains the custom application image file(s)js
: This directory contains the custom application JavaScript codejqueryMobile
: This directory (which is a newly added one) contains jQuery Mobile framework files
Finally, the index.html
file contains the application's single page whose functionality was illustrated earlier in this section.
Tip
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. The jQuery Mobile framework is one of the best mobile UI frameworks, and as such will be used in all the Apache Cordova applications developed in this module.
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:
app.css
: This is the custom style file of our Sound Recorder application- The files required by the jQuery Mobile framework, which are:
jquery.mobile-1.4.0.min.css
jquery-1.10.2.min.js
jquery.mobile-1.4.0.min.js
cordova.js
: This is the Apache Cordova JavaScript API's fileapp.js
: This is the custom JavaScript file of our Sound Recorder application
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 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:
- Tapping the
"recordSound"
button - Closing the
"recordSoundDailog"
dialog - Tapping the
"stopRecordingSound"
button - Tapping the
"playSound"
button
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:
- A call to the
startRecordingSound(recordingCallback)
function is performed. ThestartRecordingSound(recordingCallback)
function is a helper function that starts the sound recording process using the Apache Cordova Media API. ItsrecordingCallback
parameter represents a JSON object, which has therecordSuccess
andrecordError
callback attributes. TherecordSuccess
callback will be called if the recording operation is a success, and therecordError
callback will be called if the recording operation is a failure. - Then, the
"recordSoundDialog"
dialog is opened and its"soundDuration"
div is updated every second with the duration of the recorded sound.
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.
Recording and playing the audio files back
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:
src
: This refers to the URI of the media filemediaSuccess
: This refers to the callback that will be invoked if the media operation (play/record or stop function) succeedsmediaError
: This refers to the callback that will be invoked if the media operation (again a play/record or stop function) fails
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:
- If the current platform is Android, then a call to
requestApplicationDirectory(callback)
is performed in order to create an application directory (if it is not already created) called"CS_Recorder"
under the device's SD card root directory using the Apache Cordova File API. If the directory creation operation succeeds,recordVoice()
will be called by passing the application directory path as a parameter. TherecordVoice()
function starts recording the sound and saves the resulting audio file under theapplication
directory. Note that if there is no SD card in your Android device, then theapplication
directory will be created under the app's private data directory (/data/data/[app_directory]
), and the audio file will be saved under it. - In the
else
block which refers to the other supported platforms (Windows Phone 8 and iOS, which we will add using Cordova CLI in the next chapter),recordVoice()
is called without creating an application-specific directory. At the time of writing this module, in iOS and Windows Phone 8, every application has a private directory, and applications cannot store their files in any place other than this directory, using the Apache Cordova APIs. In the case of iOS, the audio files will be stored under thetmp
directory of the application'ssandbox
directory (the application's private directory). In the case of Windows Phone 8, the audio files will be stored under the application's local directory.Tip
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). - In
recordVoice()
, it starts creating a media file using theMedia
object'sstartRecord()
function. After calling the media file'sstopRecord()
function and after the success of the recording operation,recordingCallback.recordSuccess
will be called byrecordingSuccess
. TherecordingCallback.recordSuccess
function callshandleRecordSuccess
, passing the audio file's full pathmediaFilePath
as a parameter. - The following code snippet shows the
handleRecordSuccess
function:function handleRecordSuccess(currentFilePath) { $("#location").val(currentFilePath); $("#playSound").closest('.ui-btn').show(); }
- The
handleRecordSuccess
function stores the recorded audio filepath in the"location"
hidden field, which is used later by the playback button, and shows the"playSound"
button. - In
requestApplicationDirectory(callback)
, which is called in case of Android, it does the following:- Calls
window.requestFileSystem
in order to request the device filesystem before performing any file operation(s) - Calls
fileSystem.root.getDirectory
when the filesystem is ready in order to create our custom application directory - When our custom application directory is created successfully, the path of the created directory, or the existing directory, is passed to
recordVoice()
that was illustrated earlier
- Calls
- In the other application actions, the following code snippet shows the
"stopRecordingSound"
tapping and"recordSoundDialog"
closing event handlers:$("#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.
This is all you need to know about our Sound Recorder application. In order to see the complete application's source code, you can download it from the course page or get it from GitHub at https://github.com/hazems/soundRecorder.
Building and running Sound Recorder application
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.
Tip
In order to learn how to enable USB debugging in your Android device, refer to the Configuring the Android development environment section in Chapter 3, Apache Cordova Development Tools.
Summary
In this chapter, 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!
In the next chapter, we will show you how to prepare your Android, iOS, and Windows Phone development environments. Along with this, you will see how to make our Sound Recorder application works on Windows Phone 8 and iOS.