5. Anatomy of a Cordova Application

Now that we have Cordova and/or the command-line interface installed, it’s time to talk about Cordova applications and Cordova application development. In this chapter, I show you what makes a web application a Cordova application and give you a tour of the sample application the Cordova team provides.

As mentioned at the beginning of the book, a Cordova application can do anything that can be coded in standard, everyday HTML, CSS, and JavaScript. There are web applications and Cordova applications, and the distinction between them can be minor or considerable.

The sections in this chapter highlight different versions of the requisite HelloWorld application found in almost any developer book, article, or training class. For the purpose of highlighting aspects of the applications’ web content, rather than how they were created, the steps required to create the applications are omitted. Refer to the chapters that follow for specific information on how to create and test and debug Cordova application projects for several of the supported mobile platforms.

Hello World!

As with any self-respecting developer book, we’re going to start with the default HelloWorld application, then build on it to highlight different aspects of a Cordova application. The following HTML content (Listing 5.1) describes a simple web page that displays some text on a page.

Listing 5.1 HelloWorld1 Application


<!DOCTYPE HTML>
<html>
<head>
  <title>HelloWorld1</title>
</head>
<body>
  <h1>Hello World</h1>
  <p>This is a sample Cordova application</p>
</body>
</html>


If you package that page into a Cordova application and run it on a smartphone device or device emulator (in this case, an Android emulator), the app will display a simple splash screen, and then you will see something similar to what is shown in Figure 5.1.

Image

Figure 5.1 HelloWorld1 Application Running on an Android Emulator

This is technically a Cordova application because it’s a web application running within the Cordova native application container. If I hadn’t cropped the image, you would see that the web application consumes the entire screen of the emulated Android device. Even though I’m running a web application, because it’s running within a native application, there’s no browser UI being displayed and no access to browser features. It’s simply a native application rendering web content.

There is, however, nothing Cordova-ish about this application. It’s running in the Cordova native container, but it isn’t leveraging any of the APIs provided with the Cordova framework. Therefore, any web application can be packaged into a Cordova application; there’s nothing forcing you to use the Cordova APIs. If you have a simple web application that just needs a way to be deployed through a smartphone’s native app store, then using Cordova is one way to accomplish that goal.

Cordova Initialization

Now let’s take the previous example application and add some Cordova-specific stuff to it. The HellowWorld2 application, shown in Listing 5.2, has been updated to include code that recognizes when the Cordova application has completed initialization and displays an alert dialog letting you know Cordova is ready.

Listing 5.2 HelloWorld2 application


<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html;
      charset=utf-8">
    <meta name="viewport" content="user-scalable=no,
      initial-scale=1, maximum-scale=1, minimum-scale=1,
      width=device-width;" />
    <script type="text/javascript" charset="utf-8"
      src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">
      function onBodyLoad() {
        document.addEventListener("deviceready",onDeviceReady,
          false);
      }
      function onDeviceReady() {
        navigator.notification.alert("Cordova is ready!");
      }
    </script>
  </head>
  <body onload="onBodyLoad()">
    <h1>HelloWorld2</h1>
    <p>This is a sample Cordova application.</p>
  </body>
</html>



Warning

If you copy the code from any of the listings in this chapter and try it in your own Cordova applications, you may notice that there are some extra carriage returns in the middle of some of the HTML. This was done to make the code render cleanly in the printed edition of the book. To download clean versions of all of the projects in this book, access the Code section of the book’s website at www.cordovaprogramming.com or download it from Github at https://github.com/johnwargo/cordova-programming-code.


On the iPhone simulator, the application will display the screen shown in Figure 5.2.

Image

Figure 5.2 HelloWorld2 Application Running on an iOS Simulator

Within the <Head> section of the web page are two new entries: meta tags that describe the content type for the application and viewport settings. The content type setting is a standard HTML setting and should look the same as it would for any other HTML5 application.

The following viewport settings tell the embedded web browser rendering the content how much of the available screen real estate should be used for the application and how to scale the content on the screen:

<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-
scale=1, width=device-width;" />

In this case, the HTML page is configured to use the maximum height and width of the screen (through the width=device-width and height=device-height attributes) and to scale the content at 100% and not allow the user to change that setting in any way (through the initial-scale=1, maximum-scale=1, and user-scalable=no attributes).


Note

The viewport and associated attributes are not required. If they’re omitted, the browser will revert to its default behavior, which may (or may not, who knows?) result in the application’s content either consuming less of the screen area available to it or else zooming beyond it. Because there’s not much content in the HelloWorld2 application, it could, for example, consume only the upper half of the screen on some devices. You may also find that on some platforms, the settings have no effect—all the more reason to test your Cordova applications on a variety of mobile devices before release.


There’s also a new script tag in the code that loads the Cordova JavaScript library:

<script type="text/javascript" charset="utf-8" src="cordova.js"></script>

This script tag loads the core Cordova API library and makes any core Cordova  capabilities available to the program. Remember, though, that with Cordova 3, the core APIs have all been migrated to plugins. The cordova.js file contains some basic housekeeping functions.

The JavaScript code in a Cordova application does not have immediate access to the Cordova APIs after the web application has loaded. The native Cordova application container must complete its initialization process before it can respond to calls JavaScript made using the Cordova APIs. To accommodate this delay in API availability, a web developer building Cordova applications must instruct the container to notify the web application when the Cordova APIs have completed initialization. Any application processing that requires the use of the APIs should be executed by the application only after it has received its notification that the APIs are available.

In the HelloWorld2 application, this notification is accomplished through the addition of an onload event defined in the page’s body section:

<body onload="onBodyLoad()">

Within the onBodyLoad function, the code registers an event listener that instructs the application to call the onDeviceReady function when the device is ready, when the Cordova application container has finished its initialization routines and fired its deviceready event:

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

In this example application, the onDeviceReady function simply displays a Cordova alert dialog (which is different than a JavaScript alert dialog; I show you the difference in Chapter 12.) letting the user know everything’s okay:

navigator.notification.alert("Cordova is ready!")

In production applications, this function could update the UI with content created through API calls or do whatever other processing is required by the application. You’ll see an example in Listing 5.3.

Remember, most of the Cordova APIs have been removed from the container and implemented as plugins. So, to utilize the Cordova alert method, you must add the dialogs plugin to your application by opening a terminal window to your Cordova project folder and issuing the following command:

cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-dialogs.git

Leveraging Cordova APIs

Now that we know how to configure an application to wait until the Cordova APIs are available, let’s build an application that actually uses the Cordova APIs, as illustrated in the HelloWorld3 application shown in Listing 5.3.

Listing 5.3 HelloWorld3 application


<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html;
      charset=utf-8">
    <meta name="viewport" content="user-scalable=no,
      initial-scale=1, maximum-scale=1, minimum-scale=1,
      width=device-width;" />
    <script type="text/javascript" charset="utf-8"
      src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">
      function onBodyLoad() {
        document.addEventListener("deviceready", onDeviceReady,
        false);
      }
      function onDeviceReady() {
        br = "<br />";
        //Get the appInfo DOM element
        var element = document.getElementById("appInfo");
        //Replace it with specific information about the device
        //running the application
        element.innerHTML = 'Cordova Version: ' +
          device.cordova + br +
          'Platform: ' + device.platform + br +
         'Model: ' + device.model + br +
         'OS Version: ' + device.version;
       }
    </script>

  </head>
  <body onload="onBodyLoad()">
    <h1>HelloWorld3</h1>
    <p>This is a Cordova application that makes calls to the
    Cordova APIs.</p>
    <p id="appInfo">Waiting for Cordova Initialization to
    complete</p>
  </body>
</html>


Figure 5.3 shows the HelloWorld3 application running on the BlackBerry Q10 simulator.

Image

Figure 5.3 HelloWorld3 Application Running on a BlackBerry Q10 Simulator

In this version of the HelloWorld application, the code in the onDeviceReady function has been updated so the program updates a portion of the application’s content with an ID of appInfo with information about the device running the application and the version of Cordova used to build the application. Device-specific information is available via the Cordova device API (http://cordova.apache.org/docs/en/3.0.0/cordova_device_device.md.html#Device), and this sample application uses a subset of the available methods in this API.

In order for me to be able to call the Device API, I had to add the Device API plugin to the project using the CLI command:

cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git

Enhancing the User Interface of a Cordova Application

As you can see from the application examples highlighted so far, the Cordova framework doesn’t do anything to enhance the user interface (UI) of a Cordova application. The framework provides access to device-specific features and applications and leaves it up to developers to theme their applications however they see fit. Web developers should use the capabilities provided by HTML, CSS, and even JavaScript to enhance the UI of their Cordova applications as needed. I’m not going to cover mobile web UI design anywhere in this book.

As Android- and iOS-based smartphones became more popular, web developers found themselves needing to be able to build web applications that mimic the look and feel of native applications on these mobile platforms. To accommodate this need, many open source and commercial JavaScript mobile frameworks were created to simplify this task, such as jQuery Mobile (www.jquerymobile.com), Dojo Mobile (www.dojotoolkit.org/features/mobile), and Sencha Touch (www.sencha.com/products/touch).

Although not directly related to Cordova development, the use of these frameworks is very common for Cordova applications, so it’s useful to highlight them here. In this section, I discuss how to enhance the UI of a Cordova application using jQuery Mobile (jQM), an offshoot of the popular jQuery project. The jQuery and jQM libraries work together to provide some pretty useful UI elements and theming for any mobile web application.

In the HelloWorld4 application shown in Listing 5.4, I took the HelloWorld3 application and applied an enhanced UI to the application using the jQuery Mobile framework. When running, the application should have a common look across each supported device.

Listing 5.4 HelloWorld4 application


<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html;
      charset=utf-8">
    <meta name="viewport" content="user-scalable=no,
      initial-scale=1, maximum-scale=1, minimum-scale=1,
      width=device-width;" />
    <link rel="stylesheet" href="css/jquery.mobile-1.3.1.css" />
    <script type="text/javascript" charset="utf-8"
      src="js/jquery-2.0.2.js"></script>
    <script type="text/javascript" charset="utf-8"
      src="js/jquery.mobile-1.3.1.js"></script>
    <script type="text/javascript" charset="utf-8"
      src="cordova.js"></script>

    <script type="text/javascript" charset="utf-8">
      function onBodyLoad() {
        document.addEventListener("deviceready", onDeviceReady,
          false);
      }
      function onDeviceReady() {
        br = "<br />";
        //Get the appInfo DOM element
        var element = document.getElementById("appInfo");
        //Replace it with specific information about the device
        //running the application
        element.innerHTML = 'Cordova Version: ' +
          device.cordova + br +
          'Platform: ' + device.platform + br +
         'Model: ' + device.model + br +
         'OS Version: ' + device.version;
      }
    </script>

  </head>
  <body onload="onBodyLoad()">
    <div data-role="page">
      <div data-role="header" data-position="fixed">
        <h1>Hello World 4</h1>
      </div>
      <div data-role="content">
        <p>This is a Cordova application that makes calls to
        the Cordova APIs and uses the jQuery Mobile
        framework.</p>
        <p id="appInfo">Waiting for Cordova Initialization to
        complete</p>
      </div>
      <div data-role="footer" data-position="fixed">
        <h1>Cordova Programming</h1>
      </div>
    </div>
  </body>
</html>


Figure 5.4 shows the HelloWorld4 application running on the Android emulator.

Image

Figure 5.4 HelloWorld4 Application Running on an Android Emulator

Figure 5.5 shows the same application running on an iOS simulator.

Image

Figure 5.5 HelloWorld4 Application Running on an iOS Simulator

Figure 5.6 shows the same application running on a BlackBerry 10 simulator.

Image

Figure 5.6 HelloWorld4 Application Running on a BlackBerry 10 Simulator

Notice that the application looks similar across platforms. In a more complicated application, as you navigate deeper into the application, the jQM framework will automatically add mobile device platform features to the application, such as a back button on iOS and support for the escape key and menu on Android and BlackBerry applications.

In this version of the application, some additional resources have been added to the page’s header:

<link rel="stylesheet" href="css/jquery.mobile-1.3.1.css" />
<script type="text/javascript" charset="utf-8"
  src="js/jquery-2.0.2.js"></script>
<script type="text/javascript" charset="utf-8"
  src="js/jquery.mobile-1.3.1.js"></script>

The first line points to a CSS file provided by the jQM framework. It contains the style information used to render the iPhone-ish UI shown in Figure 5.6. Next come references to the jQuery and jQuery Mobile JavaScript libraries that are used to provide the customized UIs plus additional capabilities to the application. The files referenced in the example application are the full versions of the CSS and JavaScript files. These files are used during testing of the application and should be replaced with the min versions of the files, as shown in the following code snippet, before rolling the application into production.

<link rel="stylesheet" href="css/jquery.mobile-1.3.1.min.css" />
<script type="text/javascript" charset="utf-8"
  src="js/jquery-2.0.2.min.js"></script>
<script type="text/javascript" charset="utf-8"
src="js/jquery.mobile-1.3.1.min.js"></script>

The min versions are compressed, so comments, white space, line breaks, and so on are removed from the files. Compression allows the files to take up less space within the packaged application, helping to reduce the overall file size for the application, and enables these resources to load more quickly when the user launches the application.

The body of the HTML page has been updated to include several HTML div tags wrapped around the content for the application. These divs include a data-role attribute that is used by jQM to define specific areas of the content page, which are then styled appropriately depending on which role is assigned.

In Listing 5.4,  the content in the section of the page given the header data-role is styled with a gradient background and forced to the top of the page by the data-position="fixed" attribute. Similarly, the content in the section of the page given the footer data-role is styled with a gradient background and forced to the bottom of the page by the data-position="fixed" attribute. The page content defined within the data-role="content" div will be rendered between the header and footer, with the middle section scrollable as needed to display all of the content within the section. All of this is illustrated in Figures 5.4, 5.5, and 5.6.

These examples only lightly cover the capabilities of jQM; there’s so much more you can do with this framework to enhance the user experience within your Cordova applications. Refer to the jQM online documentation or several of the new books on jQM, such as Sams Teach Yourself jQuery Mobile in 24 Hours (ISBN: 0672335948), for additional information about the capabilities provided by the framework.

The Generated Web Application Files

Now that I’ve shown you how a Cordova application is crafted, let’s take a look at the Cordova application generated by the Cordova CLI. As shown in Chapter 3, “Installing the Cordova Command-Line Interface,” when the CLI generates a new Cordova application project, it creates a simple HelloCordova web application and places it in the project’s www folder. You can see an example of the generated application files in Figure 5.7.

Image

Figure 5.7 CLI-Generated Web Application Files

The project folder contains a web application folder structure that is designed to separate the different types of files into separate folders. For example, the web application’s CSS files should be placed in the css folder, JavaScript files in the js folder, and so on.

The application’s index.html file is shown in Listing 5.5; it contains many of the same HTML elements and attributes as the other examples shown throughout the chapter. One difference is that the application loads the cordova.js and other resources at the end of the file rather than at the beginning, as I have shown previously. What this approach does is allow the application to complete loading its HTML content and display the content on the screen before loading the JavaScript files. If you’re loading a bunch of JavaScript in your application, it may take some time, so this approach at least allows something to be displayed on the screen as the application’s supporting JavaScript code is loaded.

Listing 5.5 Contents of the HelloCordova index.html file


<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html;
      charset=UTF-8" />
    <meta name = "format-detection" content = "telephone=no"/>
    <meta name="viewport" content="user-scalable=no,
      initial-scale=1, maximum-scale=1, minimum-scale=1,
      width=device-width;" />
    <link rel="stylesheet" type="text/css"
      href="css/index.css" />
    <title>Hello Cordova</title>
  </head>
  <body>
    <div class="app">
      <h1>Apache Cordova</h1>
      <div id="deviceready">
        <p class="status pending blink">Connecting to Device</p>
        <p class="status complete blink hide">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>
  </body>
</html>


What the application does is display a simple page with the Cordova logo and some blinking text, “Connecting to Device,” centered beneath the logo. The JavaScript code, in the index.js file shown in Listing 5.6, is called by the application through the call to app.initialize() at the very end of the index.html.

Listing 5.6 Contents of the index.js file


var app = {
    initialize: function() {
        this.bind();
    },
    bind: function() {
        document.addEventListener('deviceready',
          this.deviceready, false);
    },
    deviceready: function() {
        //Note that this is an event handler so the scope is
        //that of the event so we need to call app.report(),
        //and not this.report()
        app.report('deviceready'),
    },
    report: function(id) {
        console.log("report:" + id);
        //Hide the .pending <p> and show the .complete <p>
        document.querySelector('#' + id + ' .pending').className
          += ' hide';
        var completeElem =
          document.querySelector('#' + id + ' .complete'),
        completeElem.className =
          completeElem.className.split('hide').join(''),
    }
};


The JavaScript code registers the deviceready listener you’ve seen in the HelloWorld3 and HelloWorld4 applications earlier in the chapter. When the deviceReady function executes, it writes some information to the console (this is described in Chapter 6, “The Mechanics of Cordova Development”), then updates the page content to indicate that the Cordova container is ready.

This application is much more complicated than it needs to be; as you can see from my previous examples, you can easily do this with much less code. However, it’s apparently the way the Cordova team wants to highlight how to build Cordova applications.


Note

In the examples I provide throughout the chapter, I deliberately simplified the application code to make it easier to teach you what a Cordova application looks like. The sample application generated by the CLI is structured more like modern HTML5 applications.

The approach you take when building your web applications is up to you: there’s no right or wrong approach. I think the CLI-generated application is more complicated than it needs to be, but as features are added to an application, it may be easier to use the approach highlighted in this section.


Figure 5.8 shows the sample HelloCordova application running on an Android emulator. When building your Cordova applications, you can start with this sample application and add in your custom code, or you can rip out the HTML and CSS files and start from scratch.

Image

Figure 5.8 HelloCordova Application Running on an Android Emulator

Wrap-Up

In this chapter, I showed you what makes an application a Cordova application plus showed you the sample application that the Cordova CLI creates for you. You now have the building blocks necessary to start building your own Cordova applications.

In the following chapters, I show you how to develop, test, and debug your Cordova applications. Chapter 6 provides general guidance on how to work with Cordova applications, and the chapters that follow provide specific guidance for several of the more popular smartphone platforms.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset