Cordova入门

Published on 2017 - 01 - 03

Requirement Checklist

  • Android SDK
  • Java
  • Gradle
  • Git
  • Node.js

Type the following commands at the command prompt.

  • adb
  • gradle
  • javac
  • git
  • npm

As long as each of these commands runs, you’re ready to install Cordova!

Installing Cordova

To install Cordova, you’ll use npm. Type this at the command prompt:

npm install -g cordova

For people on OS X, type this at the command prompt:

sudo npm install -g cordova

Making your first Cordova project

Now that you’ve gotten everything ready to go, it’s time to make your first project. Begin by changing to a new directory (for example, cordova-tests). At the command prompt, type:

cordova create myfirstproject

The default Cordova application is pretty, but it has a bit of code that I need to rip out every time I start a project. Luckily the CLI provides a --copy-from argument that lets you specify a folder to copy the initial assets (HTML, JavaScript, and CSS) from. Here’s an example:

cordova create testtwo --copy-from=/Users/ray/Dropbox/blankcordova

Digging into a Cordova project

A Cordova project is really nothing more than a folder with a few files and folders in it. The CLI is smart enough to recognize what exists inside a project so you don’t want to delete, or rename, any of the existing folders, but you can add your own. Let’s look at the folders, shown in figure 2, and describe their roles.


Let’s take it top to bottom:

  • The config.xml file —Used to configure options related to how the project is built. If you open it, you’ll see both the ID and name value you specified at the command line, or the defaults. For the most part, you won’t need to worry about modifying this, especially in the beginning.
  • The hooks folder —A way for advanced users to modify how the CLI works. Every action of the CLI, from creating projects to working with platforms to sending your code to a device, can be modified so that something happens before or after a particular action. As an example, you can have code that adds a custom platform-specific style sheet before a project is built.
  • The platforms folder —Where the native bits go for your projects. You don’t need to know native development, but if you do, there are times when you may want to see how the native projects look and you may want to modify them. In the platforms folder you’ll find one subdirectory for every platform your application is supporting. In general, this is also something else you’ll rarely touch, especially while learning, but it wouldn’t hurt to take a peek in there. Note that the folder will be empty until you add a platform.
  • The plugins folder —Where, you guessed it, plugins will be stored. Plugins are how Cordova applications do their magic—like accessing the camera.
  • The www folder —Where the heart of your Cordova application lives. This is where you’ll write HTML, JavaScript, and CSS to build out the functionality of your application.

What you’re seeing is the default Cordova structure for web assets. This is completely arbitrary. You probably want to avoid renaming index.html (Cordova projects assume that file by default; you can tweak this, but it’s easier to leave it be) but everything else can be changed to whatever you want.

Adding platforms

A Cordova project has to—or should—end up on a platform. Luckily the CLI makes it easy to set up a project for working with different platforms. You can list current platforms, add a platform, and remove a platform. This is typically something you’ll do once, early in the project, when you know what platforms you’re going to support. But you can change your mind and add a new platform.

What you’ll see in the supported list depends on what platforms (figure 3).

If you’re curious, the CLI also supports using the singular version,cordova platform, which does the same thing. Even though it’s a bit more typing, I almost always use the plural version. Adding a platform is as simple as using the add command. To add Android support you’d type cordova platforms add android. After adding a platform you’ll see a success message, as shown in figure 4.

Every project can have its own unique list of platforms it will support. Again, this is typically something you’ll do once, probably immediately after you create a project. You can run cordova platforms again to confirm what is being used, as shown in figure 5.

Removing a platform is as simple as using the remove command: cordova platforms remove android would remove Android support from your project. Go ahead and do so if you want, but be sure to add Android back. Note that you can also use rm as a shorter version: cordova rm android.

Working with Android emulators and devices

Even if you have a physical device to test your applications with, it’s sometimes easier to use an emulator for testing mobile development. Emulators not only let you test different device characteristics (screen sizes, available RAM, orientation), they also let you test different devices. So, for example, you can see how your application looks on an Android phone and then an iPad.

Open the folder where you installed the Android SDK and find the program AVD Manager.exe. Double-click to run it. On OS X, you can instead launch the program from the terminal using android avd. This launches the AVD Manager. AVD stands for Android Virtual Device, which for our purposes will mean emulators. Because you just installed the SDK, you won’t have any emulators defined and your screen will look like figure 6.

注: 如果没有将android/tools目录放到$PATH环境变量中的话,无法在shell中使用android命令,因此需要先确认android/tools目录是否已经在$PATH中。

Click Create to begin the process. While there are quite a few options here, let’s do the minimal required to create an emulator. Table 1 lists each setting we care about and what value you should use.

Setting Value
Name Set this to whatever you want. MyEmulator would be fine.
Device Choose whatever you want here as well. Nexus 5 is a good choice. But make note of the display size. If you’re on a laptop with a smaller screen, you may wish to select a device with a smaller resolution.
Target The target value represents the OS level of the device. Depending on which Android SDK installer is selected, your values here will vary.
CPU/ABI Choose ARM. This represents how the CPU will be emulated. It’s not the fastest option but it’s the safest for the most readers.
Skin Choose Skin with dynamic hardware controls.
Use host GPU Click the check box as it will speed up the emulator.

You can configure other options, but for now that’s the bare minimum and is enough to get you started. See figure 7 for what your screen will show.

You can create more emulators with specific features and OSes later on. Click OK to create the emulator. Once the emulator is created, choose it and click Start. This will open the prompt shown in figure 8.

Click Launch at this point to finish the emulator launch process. This will take a little while but, once begun, it will act like a real Android device on your computer. You’ll see an Android loading screen and a welcome screen once the virtual machine has booted, like that shown in figure 9.

Working with devices

But what about devices? If you have a real Android device, you can enable it for Cordova testing rather easily. First, connect your Android device to your computer via a USB cable. On the device, open the settings. Every device will have a slightly different UI for the Settings panel, but in general, you need to go to the About Phone menu, find the Build Number value, and click it seven times.

Yes, seriously, I know that sounds like a videogame cheat, but Google, in its infinite wisdom, decided to make it nonobvious how to enable developer options. Once done, you’ll now have a Development menu option under Settings and can enable USB Debugging. Luckily you have to do this absurdity only once.

At this point you now have at least one Android emulator, and possibly an Android device, that you can use for testing your Cordova applications!

小米手机是进入关于手机界面后,单击miui版本号7次进入开发者模式。

Sending your Cordova application to the emulator (or device)

You’re almost there. Your desired result is the application running in the emulator, as shown in figure 10.

Luckily the last step is incredibly simple. Remember that you have a Cordova project. You also have specifically told it to add platform support for Android. The last step is to get the code onto a device or an emulator. The first step in doing this is to copy the files from the www folder into the appropriate platform folder:

cordova prepare

You can optionally tell Cordova to prepare one specific platform

cordova prepare android

but if you leave off the platform, the Cordova CLI will do it for all supported platforms in the project. Next, you need to compile the platform code into the binary that can run on a device:

cordova compile

Like the prepare action, you can optionally include the platform. To make things even easier, you can use the following command:

cordova build

The build command combines both prepare and compile in one action. This action can be made specific to a platform by adding it at the end. After running the build, you’ll see quite a bit of output, but the final result should include a success message.

Okay, finally, you’re ready to see this on the emulator! That’s one more command:

cordova emulate

That’s it. Like the previous commands, this will work on all platforms in your project. And guess what? You can skip the build command too! Yep—the emulate command is smart enough to do everything—it will prepare the platform, compile it, and send it to the emulator. If you’re wondering when you’d need the other commands, they’re useful for preparing the build for submission to the app stores, as well as working with native code. You don’t have to use native code, but Cordova lets you do things with the native code if you choose. Please give your first run a few minutes to complete.

How about sending it to a device? You can probably guess:

cordova run

Again, this will try to use a connected device on any supported platform.

So how do you test this process? Open the www/index.html file from the project in your favorite editor. Any editor is acceptable as long as it doesn’t try to rewrite your code for you. Find the <h1> tag:

<h1>Apache Cordova</h1>

and change it to whatever you want. For example:

<h1>Kittens Rule</h1>

Save the file (don’t worry about backing up the original) and run cordova emulate (or cordova run) again, and you should see the screen shown in figure 11.

That’s truly all you need to do now. Continue editing the HTML and send it to your emulator. Figure 12 shows the steps by using Cordova CLI commands.

Remember, technically you can modify platforms later in the process, but typically it’s done initially. In general, the project creation and platform setup will be done first, while editing your web assets and sending it to the emulator (or device) will be the steps you do many, many times.

Building your first real application

Now that you have some idea of what a Cordova project is and how to send it to the emulator, it’s time to build a real, if rather simple, application. Your application will make use of the GitHub API to search projects. On launching the application, the end user has a simple form, like that shown in figure 13.

After your user types in a search term and clicks Search, the app will use GitHub’s API to search for projects and return the results, as shown in figure 14.

Technically this application doesn’t need Cordova. You could run this as a simple web page, but it serves as a good introduction to working with Cordova. Following the flow chart from figure 12 you know the first step is to create the project. You can create it in any folder you wish. Remember that creating a Cordova project will, by default, give you the sample application you saw earlier. That’s perfectly okay for now. But if you want, you can use another option.

The Cordova CLI can create a new application and seed it from a folder. This will essentially copy whatever is in the folder to the www folder of the new project. If you extract the zip to /Users/mary/Downloads/cordovabook, you could use the following command to do that:

cordova create searchapp --copy-from=/Users/mary/Downloads/cordovabook/c3/searchapp

Either way is fine, but using the --copy-from option will save you from typing in the code manually.

Again, following the flow chart, you know you need to add support for the Android platform. This is done by using cordova platforms add androidr.

Let’s look at the code of the application in the following listing.

Listing 1. Application homepage (index.html)

<!DOCTYPE html>
<html>
  <head>
  <meta charset="utf-8">
  <title>GitHub Search Demo</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width">
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
  <script type="text/javascript" src="app.js"></script>
  </head>

  <body>
    <input type="search" id="searchField">
    <button id="searchButton">Search</button>

    <div id="results"></div>

  </body>
</html>

There isn’t much here. You can see the basic building blocks of the application UI though: the searchField , the searchButton , and an empty div tag . Most of the work is done in the app.js file that handles recognizing the button click and performing the search. When the results are retrieved, it then writes it out to the DOM, as shown in the following listing.

Listing 2. Application JavaScript code (app.js)

/* global $,document,console */

$(document).ready(function() {

  $search = $("#searchField");
  $results = $("#results");
  $searchButton = $("#searchButton");

  $searchButton.on("click", function(e) {
    var search = $search.val();
    if(search === "") return;

    //disable button while we search
    $(this).prop("disabled",true);

    $results.html("<i>Doing a search for "+search+"</i>");

    //ok, hit the API
    $.get("https://api.github.com/search/repositories", 
    {"q":search}, function(res,code) {
      if(res.items && res.items.length) {
        var s = "<h2>Results</h2>";
        for(var i=0, len=res.items.length; i<len; i++) {
          var entry = res.items[i];
          s += "<p><strong>"+entry.name+"</strong><br/>";
          s += "By: " + entry.owner.login+"<br/>";
          s += "Updated: " + entry.updated_at+"<br/>";
          s += entry.description;
          s += "</p>";
        }
        $results.html(s);
      }
      $searchButton.prop("disabled",false);
    });

  });
});

This code uses the jQuery library to simplify both DOM access and AJAX calls and it’s assumed that most readers are familiar with it. The GitHub API (https://developer.github.com/v3/) offers quite a few different features, but all you need is the simple search mechanism. It returns an array of items that you can iterate over and display as HTML.

Pretty simple, right? But there are a few problems.

  • The application doesn’t do anything that a website couldn’t do. While that would be okay for some app markets, Apple will most likely reject something as simple as this. Cordova will provide you access to the filesystem, camera, and other device features that will truly differentiate your application from a simple web page.
  • The application isn’t really designed well. That search field and the button aren’t necessarily optimized for use on a mobile device. Even the event you listened to with jQuery (click), is a mouse event. It works, but it suffers from a delay in many devices. You should use an event that’s more appropriate, such as touchend.Later you’ll learn how to apply a good responsive design to your application and make it more mobile friendly.
  • What happens if the device is offline? Right now a whole lot of nothing. But the users will never know. They aren’t provided any sort of feedback about why their search didn’t do anything. This is also something you can easily correct with Cordova. By using a plugin, you can check the application’s online status and respond accordingly.

So is this a “bad” project? Absolutely not! You’ve created a project, built it for a platform, and seen it running on either an emulator or a device. While it may not yet make use of any cool features, you’ve practiced the development cycle for Cordova and are now ready to begin adding in all those special features that make a truly powerful mobile application.

Reference