Apache Cordova™ is a set of tools and APIs that allow you to target multiple platforms using a single code base. Normally you would write your application in JavaScript, but with FlexJS you can write your application in ActionScript and use Cordova to deploy your application onto many different types of mobile devices. Further, you can use many Cordova plug-ins to enhance your application.

Using ActionScript enables you to write code with less errors than with JavaScript because ActionScript is a strongly typed language with true classes and inheritance. Further, the compiler can detect syntactical and type errors before the code even runs. And, if you are using a FlexJS compatible IDE, code hinting and completion can speed up development.

The first step is become familiar with Cordova is using a simple application which is found in the Cordova documentation, the "Hello, World" sample. Follow this link to get started.

Create Your First Cordova App

There are two important points to take away from the Cordova example:

  1. Installing Cordova. Once you do this, you really do not need to continue with the Cordova example as the instructions on this page supersede those. However, it is a good idea to have some familiarity with the underlying process.
  2. Cordova is essentially a wrapper around your JavaScript code. Cordova does provide a variety of plug-ins (eg, to use the camera on a mobile device) which can be used with FlexJS, but the heart of the matter is that once you have set up the Cordova file structure, you really replace the supplied template JavaScript and HTML files with your own.

Once you've run the Cordova command to build the template application, you should take a look at what has been done. In the application's directory you will see a config.xml file and several sub-directories. The platforms directory contains the code needed to deploy your application onto a specific platform (eg, Android or iOS). The plugins directory contains the extras you are using for your application (eg, camera). Finally, the www directory is where the source code lies.

Inside the www directory is an index.html file and more sub-directories. Have a look at the index.html file, specifically the body element:

Cordova HTML Template
 <body>
    <div class="app">
        <h1>Apache Cordova</h1>
        <div id="deviceready" class="blink">
            <p class="event listening">Connecting to Device</p>
            <p class="event received">Device is Ready</p>
        </div>
    </div>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
</body>

The cordova.js JavaScript file is loaded along with the main code in index.js, which is here:

index.js
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');
        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
        console.log('Received Event: ' + id);
    }
};
app.initialize();

The thing to notice in this sample is the event listener for the "deviceReady" event. As your application is loaded and started on the device, the Cordova code waits until the device is capable of executing your application. When that happens, Cordova dispatches the "deviceReady" event. In the sample, this causes different CSS type selectors to come into play, changing the appearance of the UI a little.

The integration of FlexJS and Cordova hides this start-up sequence so your application can run without having to worry about it. When Cordova signals the "deviceReady", FlexJS intercepts it and dispatches its own "applicationComplete" event - which is standard for FlexJS applications to use as a trigger to begin their work in earnest. 

The key then, with Cordova and FlexJS, is the www directory that the cordova command creates in the application folder. The www directory contains the actual program that gets run on the device or browser. Since FlexJS creates HTML and JavaScript, you simply replace the contents of the www directory with your FlexJS application. The sections below explain how to use your FlexJS application with Cordova.

Requirements

  1. Install Cordova according to the instructions in the Apache Cordova web site.
  2. Install the latest FlexJS SDK and kit
  3. Set your path to include the ${FLEXJS_INSTALLDIR}/js/bin directory.

Creating the Application

To make things easier, FlexJS comes with an ANT build script called cordova-build.xml located in the FlexJS install directory. This script assumes a particular structure for your files to make it easier to build everything. Follow these instructions to create a FlexJS application to works with Cordova.

  1. Create a directory called Demo. The name is important and it should match the name of your application. 
  2. Inside the Demo directory, create a directory called src
  3. Inside the src directory place your FlexJS source files. In this case, copy the lines below into a file called Demo.mxml. Note that this file is named the same as the outer directory.
Demo.mxml
<mjs:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:js="library://ns.apache.org/flexjs/basic"
                   xmlns:mjs="library://ns.apache.org/flexjs/cordova"
                   applicationComplete="onDeviceReady()">
    <js:valuesImpl>
        <js:SimpleCSSValuesImpl />
    </js:valuesImpl>
    <fx:Script>
    	<![CDATA[
    		private function onDeviceReady():void {
    			label.text = "The device and application are ready";
    		}
    	]]>
    </fx:Script>
    <js:initialView>
        <js:ViewBase>
			<js:Label id="label" text="Hello, World" width="200" />
			<js:Circle x="300" y="300" radius="50">
				<js:fill>
					<js:SolidColor color="#0000FF" />
				</js:fill>
			</js:Circle>
			<js:Rect x="400" y="10" width="100" height="300">
				<js:fill>
					<js:SolidColor color="#88FF00" />
				</js:fill>
			</js:Rect>
        </js:ViewBase>
    </js:initialView>
</mjs:Application>

For FlexJS Cordova application, the root Application tag's namespace is "mjs" - the Cordova Application element which injects HTML into the resulting index.html file to bootstrap Cordova.

4. Once you've saved the, move one directory back to Demo and run the following command:

cordova-build
ant -f ${FLEXJS_INSTALLDIR}/cordova-build.xml

where FLEXJS_INSTALLDIR is the name of the directory containing the cordova-build.xml file.

IMPORTANT: You must have ${FLEXJS_INSTALLDIR}/js/bin in your path. In that directory is the mxmlc command that will build the JavaScript version of your FlexJS application; the mxmlc command in the ${FLEXJS_INSTALLDIR}/bin directory will not do this.

When this ANT script runs, it will create a Cordova application called Demo (the name of the outer directory) in a sub-directory called app (app/Demo) and automatically include the Android platform.  Once the Cordova application has been made, the ANT script then builds your FlexJS app into JavaScript and deposits it into a sub-directory called bin (bin/js-debug) and automatically replaces the Cordova app's www directory (app/Demo/www) with the JavaScript version of your FlexJS application.

When finished, your Demo directory will look like this:

Demo/
    src/Demo.mxml (your MXML source)
    bin/js-debug (the Javascript result of compiling Demo.mxml)
    app/Demo (the Cordova application with Android platform installed)
    app/Demo/www  (copy of bin/js-debug, runnable via Cordova on an Android device or simulator).

Running the Application

At this point you can run the Cordova application using the ANT script with the run target:

Running Application
ant -f ${FLEXJS_INSTALL}/cordova-build.xml run

You can also run the application using the cordova command line by going into the application directory (app/Demo) and running cordova run.

In the example Demo.mxml application, the Label component displays the initial text, "Hello, World". Shortly after starting up, the Label's text is replaced with "The device and application are ready". Most Cordova applications are written to wait for a Cordova event, "deviceReady". FlexJS receives this event internally and dispatches "applicationComplete" at that point so you know the application is ready to go.

ANT Options and Target

The cordova-build ANT script has a couple of other targets and options:

cleantargetRemoves the bin/js-debug directory and app/Demo/www directory contents
super-cleantarget

Removes everything except the src directory

 

-Dplatform=<platform>optionAdd this option to include a new Cordova-supported platform, such as iOS or browser.
-Dappname=<other>optionIf your main MXML file does not match the outer directory (Demo in the example), set this option to the name of the main MXML file. This will also create a matching Cordova application in the app directory.

 

Cordova Plugins

Cordova has a number of plugins you can use that do a wide variety of things. This is great when you use JavaScript to build your Cordova apps. All you need to do is go to your Cordova application directory and install the plugin, like this:

Add Plugin
cordova plugin add cordoba-plugin-geolocation

But if you plan to use FlexJS and ActionScript, some additional steps need to be done. If you were to write the code to use the plugin, something like this in your ActionScript code:

Use Plugin (JavaScript)
navigator.geolocation.getCurrentPosition(onSuccess, onError);

you will get an error as the compiler does not know what navigator is. In order to use Cordova plugins, you need to create ActionScript wrappers for them in the FlexJS framework projects. There is one started for the Geolocation plugin in the Mobile framework project in flex-asjs/frameworks/projects/Mobile.

If you look into the org.apache.cordova package, you will see a sub-package for the Geolocation framework (geolocation). Inside of this package is the Geolocation ActionScript class file. The class includes an ActionScript function to call the plugin:

Geolocation Class
		/**
		 * Gets the device current location. If successful, the onSuccess function is
		 * called with position parameter (see Cordova documentation). If failure, the
		 * onError function is called with an error parameter (.code and .message members).
		 */
		public function getCurrentPosition(onSuccess:Function, onError:Function):void
		{
			COMPILE::JS {
				navigator["geolocation"].getCurrentPosition(onSuccess, onError);
			}
		}

Within the getCurrentPosition function is the JavaScript call positioned within a COMPILE::JS block. This code block is available to framework classes and causes the code within it to be inserted, as-is, in the cross-compiled JavaScript output. 

Now your ActionScript application code can make use of it:

Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'
import org.apache.cordova.geolocation.Geolocation;
...
    var geolocation:Geolocation = new Geolocation();
    geolocation.getCurrentPosition(onSuccess, onError);
...
private function onSuccess(position):void {
    trace("Lat = "+position["coords"]["latitude"]+"; Lng = "+position["coords"]["longitude"]);
}

If you want to use a Cordova plugin in your FlexJS application, you will need to extend the FlexJS framework. Once you have done that, you can submit your code to the Apache Flex project for inclusion.

Tips

If you need to change your FlexJS application code source (MXML or ActionScript files), simply re-run the ANT command with the cordova-build.xml file.

Debug vs. Release

As stated earlier, you can use the js-release code for your Cordova application. The advantage is that it is much smaller than the js-debug version, but it will not be debuggable. If you are using the js-debug version, you can attach to it using the Google Chrome browser and debug it reasonably well.

https://developer.chrome.com/devtools/docs/remote-debugging

Using Android Studio

This section covers using Android Studio as part of your development process. If you deploy to an iOS device you will want to use Xcode.

The platforms/android directory of the Cordova project (step 2) can be opened from Android Studio as an Android project. Android Studio will analyze it and make some IDE-specific files to track it. When you do make a change to your FlexJS application, copy it (step 4) and rebuild it (step 6), Android Studio will detect that change and ask you to re-sync. After that you can re-deploy the changed app to the device or emulator.

 

  • No labels