4. Using the Cordova Command-Line Interfaces

Rather than have separate processes for each supported mobile platform, the Cordova team created two command-line interfaces (CLIs) developers can use to manage most any aspect of an Apache Cordova project. The primary CLI is the Cordova CLI; the other is Plugman, which is used indirectly by the Cordova CLI to manage plugins and directly by developers creating plugins or doing single-platform development. I will cover both of these tools in this chapter.

PhoneGap has its own CLI—it’s basically the Cordova CLI with some additional commands or command parameters added to it. I will cover the additional capabilities of the PhoneGap CLI in Chapter 13, “Using the PhoneGap CLI,” after I’ve introduced you to PhoneGap Build, where most of the additional capabilities apply.

This is an important chapter. I suggest you dig through the Cordova CLI parts of the chapter in order to understand how most developers use Apache Cordova and then come back and take a look at the Plugman stuff when you’re creating your own plugins and the PhoneGap stuff if you find you need the special capabilities PhoneGap provides.

Troubleshooting

It’s never good to start a chapter with troubleshooting information, but when working with the CLI, there are a couple of troubleshooting things you will need to know before you get started. The tips highlighted here apply to both the Cordova and Plugman CLIs.

Configuring Proxy Settings

As you saw in the previous chapter, there’s no download and installation of software for Cordova; everything you need is installed on the fly as needed. The same is true for activities that happen through usage of the Cordova CLI. When you need something, if you don’t already have it cached on your local development system, the CLI will go out to the Internet to grab it for you automatically.

Most home, independent, or small-company developers don’t have a lot of corporate networking hardware affecting how they access Internet-based resources. When in a home office, in a coffee shop, or on an airplane, the developer workstation can usually reach out and get what it needs when it needs it, provided the network connectivity is available.

Unfortunately, corporate developers, developers who work for midsize to large organizations, often have extra layers of authentication and access control in place to help protect the corporation. In many of these environments, access to external resources is controlled by a proxy. All outbound requests are forwarded to the proxy; it’s the proxy that decides whether you’re authorized to access the external resource, and it’s the proxy that retrieves the content on behalf of the system.

For the most part, your typical desktop or laptop in a proxied environment will already be configured to use the proxy—the system is preconfigured with the appropriate proxy settings, and most networked applications will automatically leverage those settings. Git and NPM, on the other hand, aren’t your typical network applications. In order to operate in a proxied environment, your development workstation may have to have some additional configuration settings changed.

If you know you’re operating in an environment with a proxy, or if you try to run Cordova CLI commands that make use of the network and get errors indicating that there’s a network access problem, you may need to configure proxy settings for Git and/or NPM.

If you need to set proxy settings, you must first determine what the proxy server configuration is. Typically all you’ll need is the proxy server host address and a port number. If you’re not sure what these are, reach out to your corporate help desk or IT administrator for help.

Git is configured using the git config command and has two settings that affect its proxy configuration: http.proxy and https.proxy. To configure the proxy settings for Git, open a terminal window and execute the following commands:

git config --global http.proxy http://PROXY_ADDRESS[:port]
git config --global https.proxy http://PROXY_ADDRESS[:port]

In these examples, replace the PROXY_ADDRESS with the host address of the proxy server and, optionally—depending on your environment—port with the network port the proxy is listening on. So, if your proxy server host address is http://proxy-srvr, and the proxy server is listening on port number 8080, you would issue the following commands:

git config --global http.proxy http://proxy-srvr:8080
git config --global https.proxy http://proxy-srvr:8080

NPM, on the other hand, is configured through the npm config command, but it essentially works the same way. To configure the proxy settings for NPM, open a terminal window and execute the following commands:

npm config set proxy http://PROXY_ADDRESS[:port]
npm config set https-proxy http://PROXY_ADDRESS[:port]

For the example used previously, you would use the following commands:

npm config set proxy http://proxy-srvr:8080
npm config set https-proxy http://proxy-srvr:8080

After you’ve successfully configured these settings, try your CLI commands again to see if the network errors have gone away.

Enabling Verbose Output

I’ve been using the Cordova CLI for a very long time. I was working on my Apache Cordova 3 Programming book and an enterprise SDK based on Cordova as the CLI was being developed, so I really see myself as part of the early group of beta testers for the CLI. In the first releases, the CLI didn’t tell you anything when it ran; it simply did its stuff and returned you to the command prompt when it was done.

When developers ran into problems, they needed some way to get information from the CLI about what happened. The CLI developers added a command-line switch, -d, that would cause the CLI to spit out more information about what it was doing as it ran. Eventually, the CLI team changed the CLI so it at least told you something as it ran, then the –d switch turned on an even more verbose output.

For example, the following Cordova command returns a little information about the prepare process:

cordova prepare

In general, as long as the command works before returning to the terminal window, that’s OK, but when working with a command that fails silently or fails with an unclear error message, it’s useful to be able to see exactly what’s happening with the command.

If you issue the following command instead:

cordova -d prepare

the terminal window will fill with many lines of text (which I won’t list here) that show the status of every step performed by the CLI during processing of the command. Some of the information is provided by the CLI commands, but some is generated by any third-party tool that might be called by the CLI.

You can also use --verbose as a command-line switch to enable the same verbose output mode.

The Cordova CLI

As Cordova applications are web applications and can be coded using any text editor, and the mobile device manufacturers use different IDEs and project structures for building native applications, there isn’t a single tool a developer can use to build Cordova applications for multiple target platforms. Instead, the Cordova team created a single tool a developer can use to interface with the tools for each mobile platform: the Cordova CLI. Think of it as a terminal-driven abstraction layer for Cordova development.

Developers use the Cordova CLI to manage most aspects of the Cordova development process. The Cordova CLI is a command-line interface that adds a suite of commands a developer can use to

Image Create cross-platform Cordova application projects

Image Add support for each of the Cordova supported mobile device platforms

Image List supported mobile device platforms

Image Remove support for a mobile device platform

Image Add a plugin to a project (this can be a core Cordova plugin, a third-party plugin, or a plugin you’ve created yourself)

Image List plugins installed in a project

Image Remove a plugin from a project

Image Prepare, compile, and build projects

Image Save project information so the project can be easily transported to another developer’s system or to a version control system

Image Serve an application project’s web content via a web server

Image Launch an application in the appropriate mobile device simulator

With these commands in place, a developer can manage the complete lifecycle of a Cordova application. Each of these options will be described in the remainder of the chapter.

When support for a new platform is added, the development team implementing the platform capabilities simply creates the necessary underlying native and JavaScript code, creates the appropriate core project files, then implements the CLI capabilities for the platform. Each platform operates differently, with its own custom code, but they all respond to the same CLI commands. What happens under the covers when the command executes doesn’t matter as long as the results are predictable and help you achieve something.

Cordova CLI Command Summary

Table 4.1 provides a summary of the available CLI commands; the sections that follow describe each of the operations in greater detail.

Image

Table 4.1 Cordova CLI Command Summary

Using the Cordova CLI

In this section, I will show you how to use the commands exposed through the Cordova CLI. I’ll cover the mechanics of the commands and what happens when each is executed; look to Chapter 5, “The Mechanics of Cordova Development,” for more information about the Cordova application project files and Chapter 15, “Cordova Development End to End,” for the end-to-end development process.

As the CLI is a command-line interface, you have to execute the CLI commands from a command line. On Windows, this is the Windows Command Prompt application, and on Macintosh OS X and Linux, this is a Terminal Window. Since the CLI is implemented using Node, which should be automatically added to the system path, you should be able to execute any Cordova CLI command from any location on your system.

Most of the commands operate on an existing Cordova project, so except for the help command (described soon) and the create command (explained in the following section), all of the Cordova CLI commands must be executed from within a Cordova project folder context. What this means is that your terminal window must be open to the project folder before issuing many of the Cordova CLI commands.

Getting Help

To learn more about what commands are available in the Cordova CLI, you can open a terminal window and get help by typing

cordova help

You can also check the CLI version number by using the following command:

cordova –v

or

cordova –version

The CLI will return to the console window the text describing the version of Cordova running on the system.

Creating a Cordova Project

Before you can do any Cordova development, you must first create an application project. To help you, the Cordova CLI includes a create command that is used to create new projects.

To create a new Cordova project, open a terminal window, navigate to the folder where you want the project folder created, then issue the following command:

cordova create project_folder

This will create a simple Cordova project structure and copy in the base web content files you can use for the application. If you supply only a folder name for the create command, the CLI will name your application project HelloCordova automatically.

You can also specify an application ID and application name using the following command:

cordova create project_folder app_id app_name

What this does is create the same project folder, but it also writes the application ID to the application’s configuration file and sets a custom name for the application.

As an example, to create a project in a folder called firstapp but with an application name of FirstApp, you would issue the following command:

cordova create firstapp com.ac4p.firstapp FirstApp

The terminal window highlighting the command and the results presented by the CLI are shown in Figure 4.1. In this particular example, I executed the command on a Macintosh, but the results would be exactly the same if the command were executed on a Windows or Linux system.

Image

Figure 4.1 Cordova CLI—Creating a New Project

When the create command runs, CLI will create the folder structure shown in Figure 4.2. The folder structure organizes the Cordova project in a way that simplifies the process of using this application across multiple mobile device platforms. Notice that the www folder is separate; this allows you to create a single web application that’s shared across multiple mobile device platforms. I’ll talk more about the web project structure and files in the next chapter. Right now all you need to know is that the web application running within your Cordova application is defined by the contents of the www folder shown in the figure.

Image

Figure 4.2 New Cordova Project Folder

The platforms folder is used to store a separate folder for each mobile device platform being supported by this application. I’ll talk more about this in the next section. The plugins folder is used to store the source code files and libraries for each plugin used by the application. I’ll talk more about this later as well.

The project’s config.xml file defines settings that describe the mobile application; this file will be covered in detail in Chapter 5.

The hooks folder may not be there by the time you read this; the Cordova team is thinking of hiding it in order to not confuse users. The functionality exposed through the hooks folder will be described in Chapter 6, “Automation and the Cordova CLI.”

If you get an error when creating a project or adding a platform, repeat the process using the –d debug flag and look for an indication of what is happening. If you see a message that says the CLI has the files it needs and is skipping the download, take a look in the folder name mentioned in the error message. If there are no files located in the specified location, you should whack the empty folder and try again.

In the sections that follow, I’ll describe the remaining CLI commands. The create command creates a new project in a subfolder of the folder from where the command was issued. The remaining commands must be issued from a terminal window pointing within the project folder.

In this section, I created a project called FirstApp and the CLI created a folder called firstapp for the project. In order for me to issue CLI commands that manipulate the FirstApp project, I must use the terminal window’s cd command to change the directory to the firstapp folder before using any of the commands described in the remaining sections.

A Cordova project’s CLI configuration is stored in the config.json file located in the project’s .cordova folder. The file is not created by default, but you can create it automatically when you first create the project. To do this, append a JSON object to the end of the create command; the JSON object should contain the key/value pairs you want written to the file. Here’s an example:

cordova create test com.ac4p.test test {"key1":"value1"}

In this example, I’m adding a configuration option key1 with a value of value1 to the file. When you execute this command, it will create the config.json file in the project’s .cordova folder and populate it with the following data:

{
  "key1": "value1"
}

Notice how I had to escape the quotation marks in the JSON object; if I hadn’t done that, the CLI would not have been able to treat the extra text I added to the command line as a JSON object.

By default, the create command will create a new Cordova project and provide a simple base web application for your project in the project’s www folder. This approach is nice if you’re just getting started with Cordova and want to get up and running as quickly as possible. Most developers simply whack the contents of that folder and replace them with their own web application files.

The Cordova CLI provides a mechanism you can use to copy in your own web application files during project create. To do this, use the --copy-from switch and a file path pointing to a folder containing the files you want to use:

cordova create firstapp com.ac4p.firstapp FirstApp --copy-from webAppFolder

In this example, webAppFolder refers to a file path pointing to the folder containing the web application files.

Many developers want to do their web application development using a different folder structure from the one Cordova imposes on them. To accommodate this, you can use the --link-to switch to link the Cordova project’s www folder to an existing folder:

cordova create firstapp com.ac4p.firstapp FirstApp -–link-to webAppFolder

When you do this, the Cordova project www folder is just a link to the webAppFolder; edit the files there, and they will be pulled into the project (through the link) during prepare, build, and so on. With this approach, you can check your web development files into a version control system, and the Cordova project is just an easily replaceable tool used to manage the build/test process.


Warning

On Windows, the CLI needs administrator privileges to create a symbolic link. You’ll therefore have to execute the Windows terminal as an administrator. To do this, right-click on the terminal window shortcut and select Run as administrator.


Platform Management

The project structure we’ve created so far has only a few empty folders plus a web application project. You could start work on your project’s web application now, but Cordova doesn’t yet know anything about the different mobile device platforms it needs to support for this project. You’ll use the Cordova platform command to manage the project files for each of the mobile device platforms your application supports.

Adding Platforms

To add support for a particular mobile device platform to your Cordova application, open a terminal window, navigate into the Cordova project folder, then issue the following command:

cordova platform add platform_name


Warning

The development tools used to create projects for the particular platform must be installed on the system and visible to the CLI before a platform can be added. The CLI may need the platform’s native tools to create a new project, so if the tools are not available to the CLI, the command will not work.


For example, if you wanted to add an Android project to your Cordova application, you would issue the following command in a terminal window pointing to the Cordova project folder:

cordova platform add android

You can also specify multiple target mobile device platforms in a single command as shown in the following example:

cordova platform add android firefoxos ios

The command will run, create the necessary folder structure for each platform, and then download and extract complete project files for each target platform. Using the project I created in the previous section as an example, I first changed to the firstapp folder, then issued the platform command as shown in Figure 4.4.

Image

Figure 4.4 Cordova CLI—Adding iOS Support to a Cordova Project

You can see from the console output that the process did quite a few things as it worked. Remember, what happens here is dictated by the tools provided by each target mobile device platform. For Android, you can see that there’s a lot going on—that’s because the CLI uses the Google-supplied ADT Ant commands to execute project-related tasks, and the Ant scripts output a lot of information about what they’re doing as they work. For Firefox OS and iOS, the project uses custom scripts provided by the Cordova platform developers to set up the projects.

If you take a look at Figure 4.5, you’ll see that my project has some new folders and files. At this point, you could fire up ADT, Xcode, or the Firefox developer tools, open the project, and run the application.

Image

Figure 4.5 Cordova Project Folder with iOS Platform Added

If you now take a look at the firstapp folder we’ve been working with, you will see that the project’s platforms folder now contains an android folder with a complete Android project inside as shown in Figure 4.6.

Image

Figure 4.6 Cordova Project Folder with Android Platform Added

You can open the Android project in the Android SDK, then run and debug the application in the Android emulator or on a physical device. I’ll show you how to do this in Chapter 7, “Android Development with Cordova.”

You don’t have to add all of your platforms at the same time; you can add them individually as I’ve shown here, or in batches. If you are working for a while with a particular set of platforms and later decide you want to add another, simply use the cordova platform add command to add your new platform to the existing project.

Listing Platforms

When you’re not sure what platforms are associated with a particular project, you can easily look at the project folder structure to figure this out. The Cordova CLI also gives you a command you can use to list the platforms that are associated with a particular Cordova project. To obtain the platform list, simply issue any of the following commands in a terminal window pointing to a Cordova project folder:

cordova platforms
cordova platform ls
cordova platform list

The CLI will return a list of the names of each of the platforms defined within the project as well as a list of platforms that can be used on this system as shown in Figure 4.7.

Image

Figure 4.7 Cordova CLI—Listing Project Platforms

Removing Platforms

If you decide that your application no longer needs to support a particular mobile platform, you can remove it by issuing the following command:

cordova platform remove platform_name

You can also use the shortcut rm instead of remove to remove platforms:

cordova platform rm platform_name

So, for my test project, if I wanted to remove the project files for the iOS project, I would issue the following command:

cordova platform remove ios

You can see the results of this operation in Figure 4.8.

Image

Figure 4.8 Cordova CLI—Removing Platforms

As you can see from the figure, the command doesn’t return anything to the terminal window on success, so unless you see an error reported, you have to assume that the command worked. If you change your mind and want to add the platform back, just use the cordova platform add command to put it back.

Updating Platforms

After Cordova 3.0 was released, the Cordova development team began work to separate the different components of the framework. Instead of the monthly releases that included everything—the CLI, platforms, plugins, and so on—the team started releasing individual components as soon as they were ready. The ultimate goal is to enable you to build Cordova applications using whatever compatible components you want.

In order to accommodate this release strategy, the team added commands to the Cordova CLI that allow a developer to update the platform code within a project. If you have an existing project and want to know whether there is updated code available for the platforms used by the project, you can open a terminal window, navigate to the Cordova project folder, and issue the following command:

cordova platforms check

The CLI will churn for a little bit, then return the list of platforms that have available updates:

android @ 4.0.0 could be updated to: 4.0.1

To perform the update, use the following command:

cordova platforms update android

The CLI will retrieve the updated platform code and update the console as it performs the update:

Running: android update project --subprojects --path
"C:Usersjwargodevac4pfirstappplatformsandroid" --target android-19
--library "CordovaLib"
Resolved location of library project to:
C:Usersjwargodevac4pfirstappplatformsandroidCordovaLib
Updated project.properties
Updated local.properties
Updated file C:Usersjwargodevac4pfirstappplatformsandroid
proguard-project.txt
Updated project.properties
Updated local.properties
Updated file C:Usersjwargodevac4pfirstappplatformsandroidCordovaLibproguard-project.txt

Android project is now at version 4.0.1

You can also use the following command format:

cordova platforms up android

With this command, you must provide the platform you want to update; you can’t just issue a generic command and update all of the platforms associated with a project.

Plugin Management

The ability to manage a Cordova project’s plugin configuration is one of the best features of the CLI. Instead of your having to manually copy around plugin files and manually edit configuration files, the CLI does it all for you. In this section, I will show you how to use the cordova plugin command to manage the plugins used in a Cordova project.

Adding Plugins

To add a plugin to an existing project, open a terminal window, navigate to the Cordova project folder, and issue the following command:

cordova plugin add path_to_plugin

In this example, the path_to_plugin parameter refers to one of the several ways you can point the CLI to a particular plugin’s installation files. The CLI can pull plugin code from most any location; if the system can access the location where the plugin files are located, you can install the plugin using the CLI.


Warning

Installing plugins using one of the Cordova CLIs is the only supported way to add plugins to a Cordova project. With previous versions of the framework, plugins were added manually by the developer copying files around and modifying configuration files. If you try to use that approach with Cordova 3.0 and beyond, you run the risk of corrupting your Cordova project.


When Cordova 3.0 was released, all of the core Cordova plugins resided on GitHub, so you would use a GitHub repository URL to point to the plugin’s files. In this scenario, to add the Camera plugin to a Cordova application, you would use the following command:

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

The core plugins eventually moved to the Cordova plugin repository and now to npmjs.org, but there still may be times where you need to pull a plugin from GitHub.

Beginning with Cordova 3.1, plugins can be installed directly from the Cordova Plugin Registry (http://plugins.cordova.io) just by specifying the plugin’s unique ID. To add the Console plugin to your application, for example, you would issue the following command from a terminal window pointing at your Cordova project folder:

cordova plugin add org.apache.cordova.console

The CLI will check the Cordova Plugin Registry for a plugin matching the ID specified, pull down the plugin code, and install it into your project. The CLI will show a simple summary of its progress installing the plugin as shown in Figure 4.9. If the plugin you are adding depends on one or more plugins to do its work, those plugins will be installed during this process as well.

Image

Figure 4.9 Cordova CLI—Adding Plugins

If you have a plugin installed locally—for example, if you are working with a third-party plugin or one you created yourself and the files are stored on the local PC—you can pass in the file path pointing to the folder where the plugin’s code is located using the following command:

cordova plugin add file_path_to_plugin_folder

If the plugin’s code is located in C:devpluginsmy_plugin_name, the command would look like this:

cordova plugin add c:devpluginsmy_plugin_name

If you are installing plugins from the local file system and those plugins have local dependencies, you can specify the plugin search path by adding the --searchpath switch to the plugin add command:

cordova plugin add c:devpluginsmy_plugin_name --searchpath c:devplugins

You should also be able to install a local plugin by name using the plugin search path:

cordova plugin add com.mycompany.myplugin --searchpath c:devplugins

You can specify multiple plugin search paths by separating each path with the appropriate delimiter for the OS. Use ; for Windows and : for Macintosh OS X and Linux. You can also use the --searchpath switch multiple times within a command, specifying a different path for each instance of the switch.

Figure 4.10 shows a Cordova project folder structure after a plugin has been added using the CLI. All of the plugin code has been added to the plugins folder within the Cordova project’s folder structure.

Image

Figure 4.10 Cordova Project plugins Folder Content

Notice that each plugin has a unique namespace built using the reverse-DNS name convention plus the plugin name. All of the Apache Cordova core plugins are referred to by the plugin name added to the end of org.apache.cordova. So, we can refer to the Camera plugin we just added to the project via the CLI as org.apache.cordova.camera. This approach to plugin naming helps reduce the potential for name conflicts among similar plugins created by different organizations.

Plugins have separate folders for the source code for each supported mobile device platform. Additionally, there are JavaScript files that are consumed by Cordova applications in the www folder. There is a lot more to know about plugins; I’ll dig deeper into the plugin project folder structure when I cover plugin development in Chapter 16, “Creating Cordova Plugins.”

Listing Plugins

To view a list of the plugins installed in a Cordova project, open a terminal window, navigate to a Cordova project folder, then issue any of the following commands:

cordova plugins
cordova plugin ls
cordova plugin list

The CLI will scan the project folder and return the list of plugins as shown in Figure 4.11.

Image

Figure 4.11 Cordova CLI—Plugin List

The Cordova project has recently started versioning plugins separately from the core Cordova releases. To help you better understand your application’s environment, the results of the plugins command also display the version number for each plugin.

Removing Plugins

To remove a plugin from a Cordova project, open a terminal window, navigate to a Cordova project folder, then issue the following command:

cordova plugin remove plugin_id

You can also use the shortcut rm instead of remove to remove plugins:

cordova plugin rm plugin_id

Regardless of how you installed the plugin, whether from a file path, Git repository, or the Cordova Plugin Registry, a plugin is defined by its ID. So, you will have to know the plugin’s ID in order to be able to successfully remove it from the project. For plugins that are added by ID using the Plugin Registry, that won’t be much of an issue since you installed the plugin using its ID, but for plugins installed from GitHub or a local file system, you can use the plugins command (described in the previous section) to determine the IDs for each of the plugins in your project before trying to remove them.

If a project has the Cordova core File plugin installed, you would remove it from the project by issuing the following command:

cordova plugin rm org.apache.cordova.file

The CLI will essentially reverse the plugin installation process by removing configuration file entries that point to the plugin and removing the plugin’s folder from the project’s plugins folder. The CLI will show the status of the process as shown in Figure 4.12.

Image

Figure 4.12 Cordova CLI—Removing Plugins


Warning

For a long time, there has been a known issue with the Cordova CLI related to its capability to successfully remove dependent plugins. You may find that you will have to manually remove dependent plugins after you remove a particular plugin. The Cordova team is aware of this problem and should be preparing a solution.


Search

If you’re looking for a particular plugin and can’t remember its ID, you can use the plugin search command to search the Cordova Plugin Registry (described in Chapter 1, “The What, How, Why, and More of Apache Cordova”) for plugins that match a particular search string. For example, if you’re looking for a plugin that handles push notifications, you can search the registry for push plugins by opening a terminal window and issuing the following command:

cordova plugin search push

The CLI will connect to the registry at http://plugins.cordova.io, search for plugins that have “push” in their ID or description, and return the following list:

cn.jpush.phonegap - JPush for cordova plugin
cn.jpush.phonegap.jpushplugin - JPush for cordova plugin
co.realtime.plugins.cordovapush - This Cordova plugin should be used with the
iOS platform together with the Realtime Messaging library (ORTC) for Push
Notifications support.
com.beyond.plugins.jpush - JPush for cordova plugin
com.blackberry.push - BlackBerry 10 Push APIs
com.cmpsoft.mobile.plugin.pushnotification - pushNotification plugin description
com.goldcipher.baidupush - no description provided
com.goldsai.baidupush - no description provided
com.hipmob.android.phonegap.plugin - Hipmob provides an in-app live chat
and helpdesk for mobile apps.
com.hipmob.ios.phonegap.plugin - Hipmob provides in-app live chat and
helpdesk for mobile apps.
com.ibm.mobile.cordova.ibmpush - Cordova IBMPush Plugin
com.infobip.push.cordova - Infobip Push Notification Plugin for Android and iOS
com.metinform.cordova.xmpp - Cordova XMPP Push Plugin for Android
com.phonegap.plugins.pushplugin - This plugin allows your application to
receive push notifications on Android, iOS, WP8 and Windows8 devices.
    Android uses Google Cloud Messaging.
    iOS uses Apple APNS Notifications.
    WP8 uses Microsoft MPNS Notifications.
    Windows8 uses Microsoft WNS Notifications.
org.chromium.gcm - This plugin allows Android apps to send/receive push messages.
org.chromium.pushmessaging - This plugin allows apps to receive push messages.
org.jboss.aerogear.cordova.push - This plugin allows your application to
receive push notifications on both Android and iOS devices. Using the
AeroGear Unified Push Server.
org.pushandplay.cordova.apprate - This plugin provide the "rate this app"
functionality into your Cordova/Phonegap application
re.notifica.cordova - This plugin allows your application to register for,
receive and handle push notifications with Notificare on both Android and iOS
devices.

Then, after perusing the list, you can select one (the PhoneGap Push plugin, for example) and add it to your project using the following command:

cordova plugin add com.phonegap.plugins.pushplugin

Save Plugins

One of the issues the Cordova team has struggled with is how to make a Cordova project transportable, easily transferred from one developer workstation to another. A Cordova project has a lot of build artifacts—the platform code, plugins, configuration files, and so on—that are not part of the app itself. The Cordova team is trying to structure the Cordova project so that it’s easy to separate the web application from the native Cordova components needed to build the app.

In the first step in this process the team added a save plugins command to the Cordova CLI that allows a developer to capture what plugins are associated with the project. I’ll explain this as I show you how it works.

To save the list of plugins, open a terminal window, navigate to a Cordova project folder, and issue the following command:

cordova save plugins

The Cordova CLI will process the plugins folder:

Saved plugin info for "org.apache.cordova.console" to config.xml
Saved plugin info for "org.apache.cordova.device" to config.xml
Saved plugin info for "org.apache.cordova.dialogs" to config.xml

A Cordova project uses a configuration file, the config.xml file, to store information about the project; I’ll explain the components of this file in the next chapter. Before issuing the save plugins command, the file contains the simple application properties shown in Listing 4.1.

Listing 4.1 Cordova Project config.xml File


<?xml version='1.0' encoding='utf-8'?>
<widget id="com.ac4p.firstApp" version="0.0.1"
  xmlns="http://www.w3.org/ns/widgets"
  xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>FirstApp</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="[email protected]" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <access origin="*" />
</widget>


After the save plugins command executes, there are some new entries in the configuration file as shown in Listing 4.2.

Listing 4.2 Updated Cordova Project config.xml File


<?xml version='1.0' encoding='utf-8'?>
<widget id="com.ac4p.firstApp" version="0.0.1"
  xmlns="http://www.w3.org/ns/widgets"
  xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>FirstApp</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="[email protected]" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <access origin="*" />
    <feature name="Console">
        <param name="id" value="org.apache.cordova.console" />
    </feature>
    <feature name="Device">
        <param name="id" value="org.apache.cordova.device" />
    </feature>
    <feature name="Notification">
        <param name="id" value="org.apache.cordova.dialogs" />
    </feature>
</widget>


For each plugin installed into the project, there is a new feature entry in the configuration file. With these features defined, if you check the config.xml file and the contents of the project’s www folder into a version control system, another developer can check out the files and more easily re-create the full project using the restore plugins command described in the following section.

Restore Plugins

After you have saved a project’s plugin configuration using the save plugins command, you can copy the project to a different system, then restore the plugins to the project by opening a terminal window, navigating to the new Cordova project folder, and issuing the following command:

cordova restore plugins

The Cordova CLI will read the config.xml file, then download and install the plugins:

Discovered org.apache.cordova.console in config.xml. Installing to the project
Discovered org.apache.cordova.device in config.xml. Installing to the project
Discovered org.apache.cordova.dialogs in config.xml. Installing to the project
Fetching plugin "org.apache.cordova.console" via plugin registry
Installing "org.apache.cordova.console" for android
Installing "org.apache.cordova.console" for firefoxos
Fetching plugin "org.apache.cordova.device" via plugin registry
Installing "org.apache.cordova.device" for android
Installing "org.apache.cordova.device" for firefoxos
Fetching plugin "org.apache.cordova.dialogs" via plugin registry
Installing "org.apache.cordova.dialogs" for android
Installing "org.apache.cordova.dialogs" for firefoxos

At this point, the new project has been updated to include the plugins from the original project.

Displaying Project Information

There are times when you will want to be able to gather a little information about a particular Cordova project: whether to learn more about it or to provide information to others during troubleshooting. To accommodate this need, the Cordova CLI team added the info command.

To obtain information about a particular Cordova project, open a terminal window, navigate to the Cordova project folder, and issue the following command:

cordova info

The CLI will peruse the project folder structure, collect some information, and display it in the console window. Listing 4.3 shows the results of the command being applied to the FirstApp project created in this chapter.

Listing 4.3 Results of the cordova info CLI Command


Collecting Data...

Node version: v0.10.32

Cordova version: 4.0.0

Config.xml file:

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.ac4p.firstapp" version="0.0.1"
  xmlns="http://www.w3.org/ns/widgets"
  xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>FirstApp</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="[email protected]" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <access origin="*" />
</widget>

Plugins:

org.apache.cordova.camera,org.apache.cordova.console,org.apache.cordova.device,
org.apache.cordova.dialogs

Android platform:

Available Android targets:
----------
id: 1 or "android-19"
     Name: Android 4.4.2
     Type: Platform
     API level: 19
     Revision: 4
     Skins: HVGA, QVGA, WQVGA400, WQVGA432, WSVGA, WVGA800 (default), WVGA854,
     WXGA720, WXGA800, WXGA800-7in
 Tag/ABIs : default/armeabi-v7a, default/x86
----------
id: 2 or "android-21"
     Name: Android 5.0
     Type: Platform
     API level: 21
     Revision: 1
     Skins: HVGA, QVGA, WQVGA400, WQVGA432, WSVGA, WVGA800 (default), WVGA854,
      WXGA720, WXGA800, WXGA800-7in
 Tag/ABIs : default/armeabi-v7a, default/x86, default/x86_64

iOS platform:

Xcode 6.1
Build version 6A1052d


The command returns the Node version, which is very important from a troubleshooting standpoint—the CLI often takes advantage of features of the most recent version of Node, so it’s always a good idea to stay with the most recent version.

Beyond those two items, the rest of the information provided is taken directly from the project or from the native SDKs used by the project. The config.xml file is used to configure the project at a high level; I’ll show you how it works in Chapter 5.

Build Management

The Cordova CLI has built-in integration with mobile device platform SDKs, so you can use the CLI to manage the application build process. In this section, I’ll describe the CLI options for managing the process of building and executing Cordova applications.

prepare

The CLI prepare command copies a Cordova project’s web application content from the www and merges folders into the appropriate platforms folders for the project. This process is described in detail in Chapter 5. You will use this command whenever you make changes to a Cordova web application’s content (in the www or merges folder). The prepare command is called automatically before some of the operations described throughout the remainder of this chapter.


Tip

Recent testing has shown that the Cordova team is experimenting with the implementation of a folder watch that will allow the Cordova CLI to automatically copy your web application content from the www folder to the appropriate platforms whenever changes are detected. I noticed this as I was doing some testing a few weeks ago, but as I wrote this chapter the “feature” didn’t seem to be working. So, as you play around with the CLI, you may find that you don’t need to prepare as often as you might think.


To use the prepare command, open a terminal window, navigate to a Cordova project folder, then issue the following command:

cordova prepare

This will copy the web application content into the appropriate folders for each of the mobile device platforms that have been added to the project.

To prepare a specific platform’s files, use the following command:

cordova prepare platform_name

So, to prepare the Android platform folder, use the following command:

cordova prepare android

The command doesn’t return anything to the terminal window on success, so unless you see an error reported, the command simply worked.

compile

In Figure 4.6, you can see that there’s a cordova folder in each platform’s folder structure. Within that folder are platform-specific build scripts used to compile a native application for that platform. The compile command initiates a compilation process by calling the build script for one or more mobile platforms depending on how you issue the command.

To use the compile command, open a terminal window, navigate to a Cordova project folder, then issue the following command:

cordova compile

To compile a specific platform’s native application, use the following command:

cordova compile platform_name

So, to compile the Android version of an application, use the following command:

cordova compile android

To compile for multiple platforms, simply pass a list of the platform names to the command:

cordova compile android ios

build

The build command is similar to compile except that it first calls prepare before executing a compile. To use the build command, open a terminal window, navigate to a Cordova project folder, then issue the following command:

cordova build

To build a specific platform’s native application, use the following command:

cordova build platform_name

So, to build the Android version of an application, use the following command:

cordova build android

To build for multiple platforms, simply pass a list of the platform names to the command:

cordova build android ios

Executing Cordova Applications

The CLI has built-in integration with mobile device platform simulators, so you can launch Cordova applications directly onto simulators or physical devices. Chapters 7 through 11 provide more detailed information about the simulators and how to configure and launch them, as well as what is required to work with physical devices from the CLI. The following sections provide a high-level overview of the relevant commands for executing a Cordova application.

run

The CLI run command automates the process of building an application and deploying it onto a physical device or device emulator. The command will first prepare the application, execute the build process, then deploy the resulting native application package to a connected device.

To run a Cordova application on all platforms that have been added to a project, open a terminal window, navigate to the Cordova project folder, then issue the following command:

cordova run

When the command executes, it will quickly update the console to let you know what it’s going to do:

Running command: /Users/jwargo/dev/firstapp/platforms/android/cordova/run
Running command: /Users/jwargo/dev/firstapp/platforms/firefoxos/cordova/run
Running command: /Users/jwargo/dev/firstapp/platforms/ios/cordova/run
run not implemented, please use firefoxos simulator to launch app

In this example, the firstapp folder has a Cordova project configured for Android, Firefox OS, and iOS. Notice that for Firefox OS, you can’t execute the application on a device or simulator from the command line; you have to use the Firefox browser tools to do so (explained in Chapter 8, “Firefox OS Development with Cordova”). For the other platforms, you’ll see a whole bunch of stuff written to the console as the CLI does all the work it needs to do to execute the application on the specified targets.

What happens next depends on what you have connected to the system running the command. If you have physical devices connected to the system using a USB cable, Android and iOS devices in this example, the CLI will deploy the application to each of the devices and launch the application. If you don’t have physical devices connected, the CLI will launch the default device emulator or simulator for each platform, then deploy the application to each emulator and launch it.

To run the application for a single platform—Android, for example—you would issue the following command:

cordova run android

There are also some switches you can pass to the run command to control how it works.

You can control which version of a particular application is executed. To run the debug version of the application, use the --debug switch:

cordova run android --debug

To run the release version of the application, use the --release switch:

cordova run android --release

If you have a device and an emulator available, you can tell the CLI which one to use through a command-line switch. To run the application on a connected device, use the --device switch:

cordova run android --device

To run the application on an emulator, use the --emulator switch:

cordova run android --emulator

If you have multiple devices and/or emulators running, you can direct the CLI to run the application on a specific target using the --target switch.

For the Android platform, the Android SDK includes a command you can use to determine the list of available devices:

adb devices

When you issue the command, the console will update with the list of devices and emulators:

List of devices attached
emulator-5554   device
213b4571        device
562a6399        device

In this example, I have an emulator running as well as two physical devices connected to the system using USB cables. To run the application on a specific target, just pass the device name to the command using the --target switch:

cordova run android --target=562a6399

The CLI will build the application and deploy it to the specified device.


Warning

For many mobile device platforms, applications will not run on physical devices without first being registered with the manufacturer (Windows Phone 8) or signed by an appropriate signing authority (BlackBerry 10, iOS). I’m deliberately omitting the details of this process from this chapter as it differs among the different supported mobile device platforms and would add some bulk to this book. I’ll cover this topic a little bit in the chapters that deal with each mobile device platform separately (Chapters 7 through 11).

Before testing Cordova applications on a physical device, make sure you have followed the manufacturer’s instructions for configuring the appropriate environment to do so.


emulate

With the first release of the Cordova CLI, the development team implemented an emulate command you could use to run an application on a device emulator. With this in place, you had separate commands to use depending on whether you wanted to execute an application on an emulator or a physical device. Since then, the emulate capabilities have been merged into the run command, and the emulate command is now simply an alias for run.

serve

When working with a mobile web application, many developers find that it’s better to test the application in a desktop browser before switching to the mobile device. This is especially important when it comes to Cordova applications as there’s an extra packaging process that has to happen before the application can be run on a device or simulator.

The CLI includes a serve command which a developer can use to launch a local web server that hosts a particular platform’s web content. It doesn’t expose any of the Cordova APIs to the browser, so all you can really test using this option is your web application’s UI. You will need to issue the CLI prepare command before launching the server to make sure your web content is up-to-date.

To use the serve command, open a terminal window, navigate to a Cordova project folder, then issue the following command:

cordova serve

Figure 4.13 shows the serve command in action. Once the command loads, it will show you what URL you must use to access the web server. Simply open your browser of choice and navigate to the specified URL to access the application content.

Image

Figure 4.13 Launching a Web Server Using the CLI

When running this process on Microsoft Windows, you may receive a security warning similar to the one shown in Figure 4.14. You will need to click the Allow access button to allow the web server to start.

Image

Figure 4.14 Windows Security Alert

By default, the server will respond to port 8000 as shown in Figure 4.13. If you want to use a different port, you can pass the port number to the CLI as shown in the following example:

cordova serve port_number

So, for the example shown previously, to serve the web application content on port 8080, you would use the following command:

cordova serve 8080

To begin using the application, open your browser of choice and navigate to the URL shown in Figure 4.13; the browser will display a page similar to what is shown in Figure 4.15.

Image

Figure 4.15 Serving a Cordova Application in a Desktop Browser

The browser window will display some information about the application including the version number, package name, and a list of all of the plugins installed into the application.

In the Platforms section of the page, you will see a list of each of the supported platforms. For each of the platforms added to the project, the serve command creates a link that takes you to the web content for that platform. This is important because, as you will learn in the next chapter, you can have different content for each target platform; this gives you the ability to test the content for each target platform separately. Nothing is done here to emulate anything about each target platform; this simply gives you access through the browser to each target platform’s files.

When you click on one of the platform links, the web application content for that platform will be loaded into the browser. You will then be able to navigate within the application and test your UI and business logic.

As you navigate through the web application in the browser, the terminal window will list each of the web application content files that are loaded by the browser as shown in Figure 4.16.

Image

Figure 4.16 cordova serve Console Entries

The serve command gives you an easy way to test all of your application’s capabilities from the desktop browser. The Cordova team has recently added the browser as a target platform to make this even easier. While it does not fully support all of the Cordova core plugins (today), you can use it to mimic many of the Cordova APIs while testing an application in the browser.

Upgrading Cordova and Cordova Projects

The Cordova team regularly publishes updates to the CLI, the platforms, and plugins, so you’ll want to check periodically to see if new stuff is available. The Cordova team doesn’t back-port bug fixes, so if you’ve encountered a bug, the fix won’t be made to the version of Cordova you’re currently using. It will come in a later version.

To make use of the most recent version of Cordova, the first step is to update the Cordova CLI. To do this for Windows, open a terminal window and issue the following command:

npm update –g cordova

For Macintosh OS X or Linux, open a terminal window and issue the following command:

sudo npm update –g cordova

With the Cordova CLI updated, you will want to update any projects you’ve been working with to the latest version. There is no project-level upgrade, so there are a few steps you have to perform to upgrade a project.


Tip

I’ve found that it’s usually prudent to update many of the dependent tools when performing a Cordova update. Before issuing the commands shown in this section, I usually first install updates to Git and NPM in order to make my life easier.


Remember from the “Platform Management” section of this chapter that there is a command you can use to determine whether updated platforms are available. The first thing you should do is perform a check for updates: open a terminal window, navigate to the Cordova project folder, and issue the following command:

cordova platforms check

If the Cordova CLI indicates that there are platforms that can be updated, use the platform update command to update them:

cordova platform update android

In this example, the Android platform is being updated. Repeat the command for each of the platforms that have an update available.

With the platforms updated, the next step is to update any plugins you have. The Cordova team recommends that you uninstall the plugins and reinstall them. Remember, though, that there may be a problem with dependent plugins, so be sure to uninstall all plugins before reinstalling them.


Note

When it comes to reinstalling the plugins in a project you are upgrading, don’t forget about the save plugins command. Before uninstalling any plugins, save the plugin list to the application’s config.xml file before uninstalling all plugins. Once you’ve removed all plugins, you can use the restore plugins command to reinstall new versions of all of your application’s plugins (and dependencies).


The Plugman CLI

The Plugman CLI is primarily used by developers who are either creating Cordova plugins or working with single-platform native application projects. Plugman is used by the Cordova CLI to manage the plugins in a Cordova application project. In this section, I’ll show you how to use all of the available commands exposed by Plugman.

Plugman CLI Command Summary

Table 4.2 provides a summary of the available Plugman CLI commands; the sections that follow describe each of the operations in greater detail.

Image

Table 4.2 Plugman CLI Command Summary

Using the Plugman CLI

In this section, I’ll describe how you can use the Plugman CLI to manage different aspects of your Cordova development project.

Creating Plugman Projects

Plugman works against an existing Cordova application project. So, before you can begin using Plugman, you must first create a new project to work with. You can do this either with the Cordova CLI or with the lower-level shell scripts provided by the Cordova project.

Cordova CLI Approach

The easiest way to do this is to use the Cordova CLI. As shown earlier in this chapter, simply open a terminal window, navigate to the folder where you want the project created, and issue the following commands:

cordova create project_folder app_id app_name
cd project_folder
cordova platform add platform_name

So, to create a project called PlugApp for Android, you would do something like the following:

cordova create plugapp com.ac4p.plugapp PlugApp
cd plugapp
cordova platform add android

To create the same application for iOS, you would do something like the following:

cordova create plugapp com.ac4p.plugapp PlugApp
cd plugapp
cordova platform add ios

The problem with this approach is that it creates a lot of unnecessary overhead to your project. As shown in Figure 4.2, a Cordova CLI project has a bunch of extra folders the Cordova CLI uses to help manage the cross-platform nature of the application. For Plugman-driven projects, you don’t need all of that stuff. The project folder’s hooks, platforms, and www folders add an unnecessary level of complexity to your project. This approach will work, but there’s a better way.

Shell Script Approach

As described in Chapter 1, inside of the Cordova CLI are platform-specific scripts that are used behind the scenes to create and manage Cordova application projects. When working with Plugman, it’s sometimes easier to simply use these files to create your project. Instructions for how to use these scripts can be found in the Command-line Tools sections of the various Cordova platform guides at http://goo.gl/lyOhju.

To get started with the shell script approach, you must first download a .zip archive containing the latest version of the Cordova tools. Right now, the files can be located at http://goo.gl/D51wGZ. Even though we’re working with Cordova 4.0, the latest download might be for an earlier version of Cordova. Once you’ve extracted the downloaded files, open the folder where you extracted the files. In the folder, you should see a separate .zip file for each supported mobile platform. Select one (or more) of the platforms and extract the files to a folder on your system. Within those extracted files, you will find a folder, typically the bin folder, that contains the script files you’ll need. You can see an example of this for Android in Figure 4.17.

Image

Figure 4.17 Android Shell Script Files

For Android, the CLI uses the create script to create a new Cordova application project. For Windows, the file is called create.bat, but for Macintosh OS and Linux, it’s a shell script called create. Open a terminal window and navigate to the folder where you want to create the new project, then issue the following command:

path_to_script_filescreate project_folder app_id app_name

For my system, the command would look like this:

D:cordova-3.4.0cordova-androidcreate plugapp com.ac4p.plugapp PlugApp

When the script runs, it will send output to the console just like the Cordova CLI does; that’s because it’s the same code doing it:

Creating Cordova project for the Android platform:
    Path: plugtest
    Package: com.ac4p.plugtest
    Name: Plugman Test
    Android target: android-19
Copying template files...
Running: android update project --subprojects --path "plugtest" --target android
-19 --library "CordovaLib"
Resolved location of library project to: C:UsersjwargodevplugtestCordovaLib
Updated and renamed default.properties to project.properties
Updated local.properties
No project name specified, using Activity name 'PlugmanTest'.
If you wish to change it, edit the first line of build.xml.
Added file C:Usersjwargodevplugtestuild.xml
Added file C:Usersjwargodevplugtestproguard-project.txt
Updated project.properties
Updated local.properties
No project name specified, using project folder name 'CordovaLib'.
If you wish to change it, edit the first line of build.xml.
Added file C:UsersjwargodevplugtestCordovaLibuild.xml
Added file C:UsersjwargodevplugtestCordovaLibproguard-project.txt

Project successfully created.

At this point, you have a complete Cordova application project for Android. Refer to the platform guides for information on the command-line options for creating projects using the script files for other platforms.

When the process finishes, the folder structure shown in Figure 4.18 will have been created. This should be similar to, but not the same as, what is shown in Figure 4.6; this is because the Cordova CLI isn’t involved and some of the extra structure it uses isn’t needed.

Image

Figure 4.18 Android Project Folder

At this point, you can open ADT and work with the project as a native Android project.


Note

There is no prepare step you need to perform before running this application. The project folder shown in Figure 4.18 is a complete native application project. Simply edit the application’s code and begin testing using the Android SDK.


The web application content for the application is located in the assets/www folder as shown in Figure 4.19. You’ll edit the content in this folder to customize the content for your application. Notice that the cordova.js file is already in the folder, something that’s normally managed for you by the Cordova CLI’s prepare command.

Image

Figure 4.19 Android Project’s Web Application Content Folder

At this point, you have a complete project and you’re ready to go. In the next section, I’ll show you how to install and remove Cordova plugins using Plugman.

Managing Plugins

Plugman can be used to add plugins to and remove plugins from a Cordova application project. In this section, I will describe how to do both.

Installing Plugins

To add plugins to an existing application project, you would open a terminal window and execute the following command:

plugman install --platform platform_name --project project_folder --plugin plugin

To add the Cordova Camera plugin to the Android project I just created, I would use the following command:

plugman install --platform android --project plugtest --plugin org.apache.cordova
.camera

When the command runs, it will update the console with details about the steps it is performing:

Fetching plugin "org.apache.cordova.camera" via plugin registry
npm http GET http://registry.cordova.io/org.apache.cordova.camera
npm http 304 http://registry.cordova.io/org.apache.cordova.camera
Installing "org.apache.cordova.camera" for android

Unlike when you are using the Cordova CLI, you don’t have to be in the project folder when issuing the command. In this example, the terminal window is poised at a level right above the project folder, so all I had to do was pass in a relative path to the project folder.

At this point, Plugman has created a plugins folder and populated it with the Android-specific plugin code. Figure 4.20 shows the plugins folder with the Camera plugin I just added, plus the Cordova Device and Dialogs plugins added just for fun.

Image

Figure 4.20 Android Project’s plugins Folder

In this example, I added plugins directly from the Cordova Plugin Registry; when working on new plugins, you can easily install an in-progress or custom plugin to the project by passing in the plugin folder to the plugman install command:

plugman install --platform android --project plugtest --plugin c:devmyplugins
plugin_name

Uninstalling Plugins

To uninstall a plugin from a project, simply open a terminal window and issue the following command:

plugman uninstall --platform platform_name --project project_folder --plugin plugin

So, for the Camera example I showed earlier, the command would be

plugman uninstall --platform android --project plugtest --plugin
org.apache.cordova.camera

As with the Cordova CLI, a plugin can be uninstalled only by using the plugin’s ID; you can easily determine the plugin’s ID from the folder name shown in Figure 4.20.

Using the Plugin Registry

The Cordova Plugin Registry is an excellent tool for helping you locate plugins for your project. As I write this, the only way to publish plugins to the registry is through Plugman. Plugman offers several commands to help you with managing entries in the registry.

The Cordova Plugin Registry currently doesn’t provide the ability for users to log in and manage their plugins using a web interface, so the commands shown here are the only options available to developers.

Add User

Before you can publish plugins to the registry, you must first define a user account. To do this, use the Plugman adduser command. Open a terminal window and execute the following command:

plugman adduser

Plugman will first prompt you for your username, password, and email address, then create the account for you:

Username: myusername
Password:
Email: [email protected]
user added

Once the process has completed, your account will be created and Plugman will write your account information to a configuration file called config located in the .plugman folder in your home directory.

Publish

With a user account created, you can publish plugins to the Cordova Plugin Registry. To do this, open a terminal window, navigate to the plugin project folder, and issue the following command:

plugman publish plugin_folder

If the terminal window is open to the folder containing the plugin project, you can publish the current folder’s plugin using the following command:

plugman publish .

Plugman will write content to the console as it works to publish the plugin:

attempting to publish plugin to registry
+ [email protected]
Plugin published

All this does is create a simple entry for the plugin in the registry. To enhance the entry with additional information about the plugin, there are two files you will need to work with: the plugin’s plugin.xml and readme.md files.

The plugin’s plugin.xml file provides information about the plugin and is used by Plugman and the Cordova CLI when managing the plugin’s installation and removal from a Cordova project. I’ll describe the file in detail in Chapter 16, but for now, the elements of the file that affect the registry entry are

<name>myplugin</name>
<description>John's Plugin</description>
<license>Apache 2.0</license>
<keywords>cordova,puppies,soccer</keywords>

These values will be used by the registry to categorize (keywords), describe (description), and identify the license for (license) the plugin.

If you add a file called readme.md to a plugin project’s folder, the content of the file will be used in the registry to provide additional information about the plugin.

You can see the results of the publish process in Figure 4.21; notice that the Description, Keywords, and Read Me are all populated with information.

Image

Figure 4.21 Cordova Plugin Registry Entry

With this in place, you or other developers can now install your plugin directly from the registry using the plugman install command described previously or the Cordova CLI’s cordova plugin add command:

cordova plugin add com.johnwargo.myplugin

To publish an update to the plugin, edit the plugin’s version information in the plugin’s plugin.xml file and repeat the publish process. The plugin version is stored in the first line of the plugin.xml file:

<plugin id="com.johnwargo.myplugin" version="0.0.4"
  xmlns="http://apache.org/cordova/ns/plugins/1.0"
  xmlns:android="http://schemas.android.com/apk/res/android">

In this example, you can see that the plugin’s current version is 0.0.4, which is also the same value that’s shown in Figure 4.21.

Unpublish

If you decide that you no longer want the plugin to be available in the registry, you can unpublish the plugin by opening a terminal window and issuing the following command:

plugman unpublish plugin_id

So, for the example plugin I’ve been using throughout this chapter, the command would be

plugman unpublish com.johnwargo.myplugin

Plugman will write content to the console as it works to unpublish the plugin:

attempting to unpublish plugin from registry
Plugin unpublished

That’s it; there’s not much to it.

Search

Sometimes when you’re building a Cordova application, you’ll want to add some specific functionality to it. You could extend the Cordova container by writing your own plugin, but an easier approach is to see if someone else has already written the plugin you need. You can go to the Cordova Plugin Registry web site (http://plugins.cordova.io) and search for plugins there, or you can use the plugman search command to do it directly from a terminal window.

To search using Plugman, open a terminal window and execute the following command:

plugman search search_term

For example, if I were looking for a push plugin, I would use this command:

plugman search push

Plugman will connect to the registry and execute the search against the information provided by the registry. An example of the search results is shown earlier in the chapter under the cordova plugin search command. With the search results, you can select a plugin, add it to your project, and begin testing.

Info

To view detailed information about a particular plugin, open a terminal window and execute the following command:

plugman info plugin_id

For the Cordova Camera plugin, the command would be

plugman info org.apache.cordova.camera

The command returns the contents of the plugin’s entry in the registry. Since the plugin’s entry contains a lot of information, the results may be difficult to read in the terminal window.

Plugman Configuration

Plugman stores its configuration information in a file located in the user’s home folder. To view the current settings for the user, open a terminal window and issue one of the following commands:

plugman config get
plugman config ls

Plugman will display the current settings in the terminal window:

; cli configs
$0 = "node C:\Users\jwargo\AppData\Roaming\npm\node_modules\plugman\main.js"
cache = "C:\Users\jwargo\.plugman\cache"
email = "[email protected]"
registry = "http://registry.cordova.io/"
userconfig = "C:\Users\jwargo\.plugman\config"
username = "myusername"

; userconfig C:Usersjwargo.plugmanconfig
email = " [email protected]""
username = "myusername"

; node bin location = D:Program Files odejs ode.exe
; cwd = C:Usersjwargodevmyplugin
; HOME = C:Usersjwargo
; 'npm config ls -l' to show all defaults.

done

Of the information presented, the most important item is the registry setting. By default, Plugman comes configured to use the Cordova Plugin Registry (http://plugins.cordova.io). If you want to use plugins residing in another repository, you can easily change the registry Plugman uses. You can determine the current registry setting by opening a terminal window and issuing the following command:

plugman config get registry

Plugman will churn for a few seconds, then return

http://registry.cordova.io/

To change where Plugman gets and puts its plugins, you can use the following command:

plugman config set registry http://path_to_registry

There’s no information in the Cordova documentation that describes what this registry should look like, but the existing registry uses NPM behind the scenes, so I can only assume it looks and feels like npmjs.org.

Owner

Multiple users can have the ability to publish updates to plugins published to the Cordova Plugin Registry. Users who have the ability to publish updates are called owners of the plugin. To manage a particular plugin’s owners list, you would use the plugman owner command.

To view a list of the current owners for a particular plugin, open a terminal window and issue the following command:

plugman owner ls plugin_id

For the example plugin I’ve shown throughout the Plugman section, you would use the following command:

plugman owner ls com.johnwargo.myplugin

To add a Cordova Plugin Registry user account as an owner of the plugin, you would use the following command:

plugman owner add username plugin_id

For the example plugin I’ve shown throughout the Plugman section, you would use the following command:

plugman owner add myusername com.johnwargo.myplugin

To remove an owner from the plugin, use the following command:

plugman owner rm username plugin_id

For the example plugin I’ve shown throughout the Plugman section, you would use the following command:

plugman owner rm myusername com.johnwargo.myplugin

Creating Plugins

As you’ll learn in Chapter 16, a Cordova plugin is typically a project with some JavaScript code and native application code for each supported platform. A developer has to create the JavaScript code, then add the native code to support the JavaScript interface and update a configuration file describing all of it.

Plugman has commands that can help you with the process of creating plugins, including setting up the necessary folder structure and creating (and updating) the configuration file. The commands described in this section help you create plugins and add support for additional mobile platforms to your new plugin.

Create

To create a new Cordova plugin, open a terminal window, navigate to the folder where you want the plugin project created, then issue the following command:

plugman create --name plugin_name --plugin_id plugin_id --plugin_version 0.0.1

As an example, I created a new plugin using the following command:

plugman create --name myplugin --plugin_id com.johnwargo.myplugin
--plugin_version 0.0.1

What Plugman did was create a new subfolder called myplugin, then add the folder structure and files shown in Figure 4.22. One of the first things you’ll want to do is add a readme.md file to the project folder.

Image

Figure 4.22 Plugin Project Folder

The plugin.xml file is an XML file that describes the plugin; Plugman and the Cordova CLI will use this file to determine what files to install for each supported platform plus what interfaces the plugin exposes to an application using the plugin. Listing 4.4 shows the plugin’s default plugin.xml file with description, license, and keywords elements added to the file as described previously.

Listing 4.4 plugin.xml File


<?xml version='1.0' encoding='utf-8'?>
<plugin id="com.johnwargo.myplugin" version="0.0.1" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
  <name>myplugin</name>
  <description>John's Plugin</description>
  <license>Apache 2.0</license>
  <keywords>cordova,puppies,soccer</keywords>
  <js-module name="myplugin" src="www/myplugin.js">
    <clobbers target="cordova.plugins.myplugin" />
  </js-module>
</plugin>


I’ll describe the contents of this file in greater detail when I cover creating plugins in Chapter 16.

The plugin’s www folder contains a single file called myplugin.js, shown in Listing 4.5. This file is intended to describe the interface your application interacts with when using the plugin. The sample file created by Plugman simply creates a function called coolMethod which you can extend, or replace, depending on your plugin’s requirements. Again, see Chapter 16 for details on what you should do next.

Listing 4.5 myplugin.js File


var exec = require('cordova/exec'),

exports.coolMethod = function(arg0, success, error) {
  exec(success, error, "myplugin", "coolMethod", [arg0]);
};


The plugin project’s src folder should contain the native code your plugin uses. When you first create the project, the src folder is empty. In the next section, I’ll describe how to add platform support to your plugin project.

Platform

Once you have a plugin project created, you’ll use the plugman platform command to add support for one or more mobile device platforms. To use this command, open a terminal window, navigate to the plugin project folder, and issue the following command:

plugman platform add --platform_name platformName


Note

Notice that this is one of the few Plugman commands that works on the current folder; most other commands accept a folder as a parameter. Be sure you’re in the right folder when issuing this command.


So, to add support for the Android platform to your plugin, you would use the following command:

plugman platform add --platform_name android

Unlike when you use the Cordova CLI, you can’t add multiple platforms at the same time, so to add another platform such as iOS, you would use the following command:

plugman platform add --platform_name ios

Each time you add a platform, Plugman will add a folder for the specified platform to the src folder as shown in Figure 4.23. Inside the folder, you’ll find a starter file for the plugin’s native source code. In this case, since it’s for an Android plugin, Plugman has created a myplugin.java file for you to extend for your plugin. For iOS, Plugman will create a myplugin.m file for you to flesh out for your plugin.

Image

Figure 4.23 Plugin src Folder for Android

Refer to Chapter 16 for information on how to write the code for your plugin.

As Plugman adds platform support to your plugin project, it also updates the plugin.xml file with information about each platform as shown in Listing 4.6. Sorry to say this again, but you’ll learn more about this in Chapter 16.

Listing 4.6 Updated plugin.xml File


<?xml version='1.0' encoding='utf-8' ?>
<plugin id="com.johnwargo.myplugin" version="0.0.1"
  xmlns="http://apache.org/cordova/ns/plugins/1.0"
  xmlns:android="http://schemas.android.com/apk/res/android">
  <name>myplugin</name>
  <description>John's Plugin</description>
  <license>Apache 2.0</license>
  <keywords>cordova,puppies,soccer</keywords>
  <js-module name="myplugin" src="www/myplugin.js">
    <clobbers target="cordova.plugins.myplugin" />
  </js-module>
  <platform name="android">
    <config-file parent="/*" target="res/xml/config.xml">
      <feature name="myplugin">
        <param name="android-package"
          value="com.johnwargo.myplugin.myplugin" />
      </feature>
    </config-file>
    <config-file parent="/*" target="AndroidManifest.xml" />
    <source-file src="src/android/myplugin.java"
      target-dir="src/com/johnwargo/myplugin/myplugin" />
  </platform>
  <platform name="ios">
    <config-file parent="/*" target="config.xml">
      <feature name="myplugin">
        <param name="ios-package" value="myplugin" />
      </feature>
    </config-file>
    <source-file src="src/ios/myplugin.m" />
  </platform>
</plugin>


To remove support for a particular platform, open a terminal window, navigate to the plugin project folder, and issue the following command:

plugman platform remove --platform_name platformName

As an example, to remove support for iOS from your plugin project, issue the following command:

plugman platform remove --platform_name ios

Wrap-Up

In this chapter, I showed you how to utilize the Cordova CLI to manage your Cordova application projects and how to use Plugman to manage plugins, interact with the Cordova Plugin Registry, and create your own plugins. The capabilities provided by the CLI dramatically simplify the cross-platform development process and managing your Cordova application’s plugin configuration.

In the next chapter, I’ll describe the mechanics of Cordova development: how you’ll interact with Cordova and your application projects using the CLI and other tools available to Cordova developers.

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

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