An Introduction to Cordova: Example

In the first tutorial of this introduction to Cordova, you learned about what Cordova is, how it works under the hood, and what type of apps you can build with it. In this tutorial, you’ll move on to the practical part and actually get your hands dirty by building your first Cordova app.

First, I’ll show you how to install everything that you need to get up and running with Cordova. You’ll then build a hello world app that utilizes a couple of plugins, a user interface framework, and the Crosswalk web view. At the end of this tutorial, you’ll deploy your app to an Android device.

1. Installing the Dependencies

Step 1: Git

Git is a version control system. It is used to pull plugins that you want to add to your Cordova project. To install Git, visit the downloads page and select the installer for your operating system.

Step 2: Node.js

Node.js is a runtime environment for web applications that are powered by JavaScript. It comes with a package manager called Node Package Manager or npm, which is used by developers to distribute tools and libraries. Cordova and its plugins are distributed using npm and that’s why we need to install it.

If you’re on Windows or OS X, then you can install Node.js using the installer that’s available from their downloads page. If you’re on Ubuntu or another Linux distribution, then you can install node with the package manager that comes with your operating system. For Ubuntu, you can install Node.js using the following commands:

Step 3: Java

The next component we need to install is Java. We need Java, because we will be deploying the hello world app to an Android device. Native Android apps are written in Java and that’s why we need to have Java installed.

To install Java, visit the Java downloads page and click on the Free Java Download button to bring up a list of the available installers for your operating system. Download an installer for your operating system and install Java.

Step 4: Android SDK

Since we’re going to deploy the app to an Android device, we need to install the Software Development Kit (SDK) for Android. Visit Android Studio and SDK Tools and, under SK Tools Only, download the corresponding package for your operating system.

For Windows, there’s already an installer which you can use to select the packages that you want to install. For OS X and Linux, you have to extract the archive. Once extracted, open the .bashrc file located in your home directory and add the path to the Android SDK and SDK tools:

Replace /media/wern/Files/downloads/ with the actual path to the Android SDK on your machine. You can then use the source command to reload the .bashrc file:

Doing this allows you to execute the android command from the command line, launching the Android SDK Manager. This enables you to select which packages you want to install on your machine. Cordova only needs the following packages:

  • Android SDK Tools
  • Android SDK Platform-tools
  • SDK Platform of the latest Android API
  • Android SDK Build-tools for the latest Android API (Android 6.0 at the time of writing)

With the above packages selected, it should look like this on your machine:

android sdk manager

Click the install button to start the installation process. This will open a window that asks you to confirm the packages to be installed. Click the Accept License radio button to confirm and click the install button. This might take a while depending on your internet connection.

install packages

Step 5: Cordova

Once you have installed the necessary dependencies on your machine, you’re ready to install Cordova. Execute the following command from the command line:

The -g option tells npm to install Cordova globally, which means that you can use the Cordova command line tools from anywhere.

2. Building the App

We’re now ready to build a simple hello world app with Cordova. We will create an app that allows the user to take a photo with the camera plugin and share the photo with the PhoneGap social sharing plugin. Finally, we will also be using Crosswalk.

To create a new Cordova app, open a new terminal window and execute the cordova create command:

The cordova create command accepts the following arguments:

  • directory: This is the directory that will be created to contain the files of your app.
  • identifier: This is the identifier that you give your app. The common naming convention is reverse domain name notation, suc as com.companyname.appname.
  • title: This is the title of your app.

Once the command has finished executing, you will see a photosharer folder with the following contents:

  • hooks: Hooks are pieces of code that you want to execute at certain points when building an app with Cordova. This folder is where you put your hooks. We won’t be working with hooks in this tutorial since we won’t be needing them. For now, remember that you can use hooks to execute specific code that can process, copy, or remove files before or after a specific cordova command is executed.
  • platforms: This is where files needed by all your target platforms are stored. Examples of a platform include the browser, Android, iOS, and Windows Phone.
  • plugins: This is where plugins that you’ve installed for your app are stored.
  • www: This folder contains the source code for the user interface of the app. You’ll be spending most of your time in this folder.
  • config.xml: This is the configuration file that is used for controlling the basic aspects and behavior of your app.

Now that you know what each of the folders in a Cordova app is for, it’s time to move and start building the app. Open index.html, which is located in the www directory. This is the default page that Cordova serves. Cordova apps are best written as a single page application so the user doesn’t see the page reloading every time a page in the app is accessed. A single page application is nothing more than a web application that only uses one HTML page. Templates are then used to inject different states of the application as needed.

By default, index.html contains the following code:

You can see that there’s nothing really special. It’s a simple HTML file. The only thing that’s different are the meta tags. Let me walk you through some of them.

The first meta tag specifies the content security policy. This makes the Cordova application secure from cross-site scripting (XSS) attacks. Any script that an attacker manages to inject into the page would simply refuse to be loaded with this meta tag in place.

The format-detection meta tag automatically converts phone numbers into links. The user can then click the link to make a call to that phone number.

The msapplication-tap-highlight meta tag disables the grey tap highlight on Windows Phone 8 and later. If you’re not planning to deploy on a Windows Phone device, you can safely remove this tag.

The next tag is the viewport meta tag. Let’s go through the attributes of this tag from left to right. The tag first specifies that the user shouldn’t be able to zoom the page in or out. Next, the initial-scale is set to 1. This means that the content is loaded at 100%. The maximum-scale and minimum-scale are both set to 1. This sets the minimum and maximum values that the user can set for the zoom level. The width attribute specifies that the maximum device width is used for the content.

Next up is the default stylesheet. This stylesheet contains basic styling for the app.

Inside the body tag lives the markup for showing the status of Cordova. The p element with a class of listening is shown when the device APIs aren’t fully loaded yet. It is hidden when the device APIs are ready. At that point, the p element below it is shown instead. This markup is specific to the default Cordova application so we can safely remove it later.

We then encounter two script tags. The first one includes cordova.js. This file provides a unified API for accessing native device features. You won’t find this file under the www directory, because it is injected to the specific platform when you build your app. This means that there’s a different version of cordova.js depending on the platform the app is running on.

The second script tag includes index.js. This file is specific to the default application that’s created when you start a new Cordova project. All it does, is execute specific code when a specific event happens.

If you open the file, you will notice that the receivedEvent function is responsible for hiding and showing the two p elements we encountered earlier. It’s being triggered by the onDeviceReady event. So the event identifier that’s passed to the receivedEvent function is deviceready.

You’ve waited long enough. It’s now time to get your hands dirty. Let’s first make sure that everything looks good by making use of Ratchet, a front end framework for building mobile web apps. You can download it from their homepage or install it with Bower by executing the following command:

Copy the files to the www/lib directory of your Cordova project and link the stylesheet to your index.html file.

Remove the default markup inside the body tag:

And replace it with the following:

The above markup adds a button for taking a photo. Below it is the div tag for sharing the photo. It has a text field for entering the caption and a button for sharing.

Grab a copy of jQuery and save it to the www/lib directory.

Create an events.js file in the www/js directory and add the following code to it:

Add a script tag for events.js below the one for jQuery.

Let’s see what we’ve got so far. We first wrap everything in an immediately invoked function expression. This way, the script doesn’t conflict with another script that we might include later on.

Next, we add a click event listener to the button for taking photos.

Inside it are the options for the camera plugin.

Here’s a brief description of each of the options that we use:

  • quality: This option lets us specify the quality of the photo that will be saved, 100 being the highest and 0 being the lowest.
  • destinationType: With this option, we specify the type of the resulting photo. This can have a value of DATA_URL, which returns a base64 encoded string, or FILE_URI, which returns the path to the file on the local file system.
  • encodingType: This option defines how the photo will be encoded. The possible values are JPEG and PNG.
  • targetWidth: Use this option to specify the width of the photo.
  • targetHeight: Use this option to specify the height of the photo.

Next, we have the code that launches the default camera app of the device. It has two callback functions. The first one is the success callback, which is executed when the photo is successfully captured. The URL of the image is passed as an argument. It is then used as the value for the src attribute of the img element. If there was an error, the second callback function is executed. If something goes wrong, we show an alert to notify the user about the error.

Once a photo has been captured, the #share-container div is shown to the user. This contains the share button to which we add a click event. This uses the social sharing plugin. In the code below, we pass in the value entered in the caption text field and the file path to the photo. The social sharing plugin then launches the default sharing window of the operating system. At that point, the user can select the application in which to share the photo.

3. Installing Plugins

In the previous section, we already used two plugins, the camera plugin and the social sharing plugin. But you may have noticed that we haven’t installed any of them yet. In this section, we’ll do just that.

Installing plugins is simple if you already know the specific plugin that you want to install. All you have to do is determine the plugin identifier. This is usually the name given to the GitHub repository or the package name on the npm website.

The identifier of the camera plugin is cordova-plugin-camera. Installing the plugin is as simple as executing the cordova plugin add command and passing in the identifier of the plugin:

For the social sharing plugin, things are a bit different since it doesn’t comply with the naming convention:

If you’re not sure what plugin you need to install, then simply Google it. There’s also the Cordova plugins website that you can use to search for Cordova plugins. In the screenshot below, I was looking for a social sharing plugin. The results are by default ordered by quality. This means that plugins are arranged from the most awesome to least awesome. I’m not really sure what metric they used for this though. Aside from that you can also filter the results to only show plugins that supports specific platforms. It also comes with a nice copy to clipboard functionality that allows you to copy the command for installing the plugin.

cordova plugins

One final note about installing plugins is that you have to build the app every time you install a new plugin. Installing a plugin doesn’t automatically copy it to the different platforms to which you want to deploy.

4. Adding Crosswalk

Crosswalk is a pluggable web view for Cordova apps based on Chromium and Blink. By using Crosswalk, you replace the default web view that is used by Cordova. This allows you to use browser features such as WebRTC, WebAudio, and Web Components in your apps. It also improves the performance of your app. The only known drawbacks are an increased memory footprint and the size of the installer file.

Crosswalk is distributed as a plugin. You can install it with the following command:

The next time you build the app, it should install the web view for the platform you’re deploying to. It might take a while depending on your internet connection. But it only does this the first time you build the app after installing Crosswalk. This is because it has to download all the necessary files from a remote server and then perform the compilation.

After the build process, it should yield two separate apk files for Android, one for the armv7 architecture and one for x86. Crosswalk makes a separate package file for each of these architectures, because the apk file would otherwise become large if they’re packaged into one. Luckily, Google’s Play store allows developers to upload different versions of an apk file for the same app.

5. Configuring the App

If you want to update the configuration of your app at some point, then you can edit config.xml, which is located at the root of your project. This is what config.xml looks like by default:

You can update the identifier of your app:

The versioning uses the semantic versioning convention (major.minor.patch):

Update the name tag to update the name of your app:

Or the description:

You can also specify which HTML file is rendered in the web view when the app is opened.

The configuration file also defines the domains the app is allowed to access. By default, a Cordova app is configured to allow access to all (*) domains.

This isn’t recommended. It makes the app less secure, because it can make requests to external domains that might contain malicious content. That’s why the whitelist plugin is installed by default. This gives developers fine control over which domains or intents (tel, geo, sms) are allowed in the app.

For more information on app configuration, check out the documentation for the config.xml file.

6. Deploying the App

In this section, I’ll be walking you through the steps involved to prepare and deploy a Cordova app to Google’s Play store.

Step 1: Adding Platforms

The first thing you need to do is add the platform(s) you’re targeting. To list the platforms you can target with Cordova, execute the cordova platform list command. This command lists the platforms that you’ve installed as well as the platforms that are available for publication:

As you can see, I already installed two platforms, browser and android. You can do the same by executing the following commands:

The browser platform is mainly used for testing your app in the browser. This is done by executing the cordova serve command. This command creates a server that serves your app on a specific port. By default, it’s serving your app on port 8000. You can view it by opening a browser and browsing to http://localhost:8000/browser/www.

You can use the emulator in your browser to display the app in a smaller screen. In Google Chrome, for example, you can click on the mobile icon in the upper left of the developer tools.

The cordova serve command copies your source files to the platforms/browser directory. This means that any time you make a change to the files in the www directory, you have to restart the server for the changes to take effect. If you want to learn more about this topic, then I recommend you check out Grunt or Gulp, two automation tools that help you copy files to the browser platform every time you make a change to the source code. Here’s what the app looks like in the browser:

cordova serve browser

Next, we have the Android platform. If you open the platforms/android directory, you’ll see a lot of folders and files. Most of them are files used by Cordova during build time so you don’t really have to worry about those. In fact, you don’t really want to mess with the files in this directory unless it’s really necssary. However, you have to keep in mind what the following files and folders are for, because you may need to work with them later.

  • assets: This is where the files from the www directory are copied to.
  • build: Once you build your app, this is where the build files are stored. For Android, they are saved under the build/outputs/apk directory.
  • AndroidManifest.xml: This file is specific to the Android platform. This is the app configuration. Anything that you’ve included in config.xml is copied over to this file. When you install a plugin, the plugin adds an entry to this file for the specific permissions that it uses. If there’s an issue with a specific plugin, this is where you would usually take a look, because it’s possible that the plugin hasn’t added the necessary permissions to this file.
  • res: Any assets that your app uses are copied over to this directory. This includes images, sound files, welcome screens, etc.
  • src: This folder contains platform specific code from the plugins that you’ve installed.

Step 2: Generating the App Build

After adding the Android platform, it’s time to build the app. This process will generate the package or installer for each of the platforms that you have added to your project. For Android, it will be an .apk file. You can use the following command to initiate the build process for the Android platform:

If you want to build for multiple platforms, simply ommit the platform parameter:

Note that the above two commands don’t generate an .apk that’s ready for submission to Google’s Play store. By default, the cordova build command generates a debug version of your app. This version of the app is intended for testing by the developer. The only difference between the two is the certificate used for signing the app. The debug version of an app is signed with a certificate from the android SDK while the release version of the app is signed with a certificate that’s generated by the developer. This means that, when you run the cordova build android command, it will automatically sign the generated apk file for you. If you want to generate a release version of the app, you have to add the --release option:

This tells Cordova that this app will be signed by the developer later on.

Step 3: Signing the App

We’re now ready to sign the app. Before we do, I’d like to make sure we’re on the same page. What does signing the app actually do and why is it needed? To put it simply, you need to sign the app so that you can be identified as the author of the app. This proves that the app came from you.

On Android, this can be done using a keystore file. You can use this file for signing your app. To generate a keystore, you use the keytool which you can find in the sdk/tools directory of your Android SDK installation path. Since we already added the path to the SDK tools earlier, we should be able to execute the keytool command from the command line.

Here’s a breakdown of each of the options and arguments that we’ve passed in. The options are the ones prefixed with a dash and the arguments are the ones without a dash.

  • genkey: the command to generate the key
  • keystore: the file name of the keystore
  • alias: the alias that you want to give to the key
  • keyalg: the algorithm to be used for generating the key
  • keysize: the size of the key in bytes
  • validity: how long (in days) the keystore should be valid

Next, we use another tool called jarsigner to sign the app with the keystore that we’ve generated. Navigate to the directory where you have the unsigned release version of the app:

Next, execute the following command:

This command will ask for the password that you’ve entered when you generated the keystore. Enter the password to start the signing process.

Let’s break the command down:

  • -verbose: specifies that the command should output all information while signing the apk file
  • sigalg: the signing algorithm to be used, in this case we’re using SHA1withRSA
  • digestalg: the message digest algorithm to use
  • keystore: the path to the keystore file
  • android-release-unsigned.apk the path to the unsigned release version of the apk file
  • photosharer: the alias that you’ve specified earlier when you generated the keystore file

Finally, we need to make sure the app performs at its best. To do that, we use the Zipalign tool. Zipalign is installed in the build-tools directory of your Android SDK install path. You can go ahead and copy it to the tools directory of your Android SDK install path. This allows us to use it from any terminal window since we already added the tools directory to the .bashrc file earlier. Once that’s done, you can execute the command below. The -v option provides us with verbose output. 4 is an integer that defines the byte-alignment boundaries. This should always be set to 4. android-release-unsigned.apk is the path to the apk file that we want to optimize. photosharer.apk is the name of the output file.

After it finishes executing, you should be able to upload the photosharer.apk file to the Play store. If you used Crosswalk, you need to do the same process for both the armv7 and the x86 version of the app.

Learn More in Our Cordova Course

If you like to learn more about Cordova, then check out Reggie Dawson’s course on Cordova. Reggie introduces you to the platform and helps you create a Cordova app from scratch. Take a look at the below video to get a taste of the course.

Conclusion

In this tutorial, you have learned how to get started with Cordova for your mobile projects. As you have seen, Cordova allows you to build mobile apps with web technologies, but it also gives you access to native device capabilities. This reduces development time since you don’t need to develop a separate app for every platform that you’re planning to support.

Moving forward, I recommend you go and explore some of the frameworks that are available for Cordova. This includes Ionic, Onsen UI, Mobile Angular UI, and Framework7. Frameworks do some of the heavy lifting for you so you don’t have to implement it on your own. Things, such as routing, user interface, animations, and the overall structure of your code base are handled by one of these frameworks. This allows you to concentrate on the functionality of the app instead.

Tags:

Comments

Related Articles