Components

If you use the Flex framework, try the Tour de Flex application (see Figure 18-4). It is a good starting point for examples using components to develop AIR for Android applications. You can get it from the Android Market.

Figure 18-4. The Tour de Flex application
Figure 18-4. The Tour de Flex application

Flash Builder was initially not suited for mobile development. Components, such as the DataGrid or the Chart, were too complex and too large for the memory footprint.

Some work has been done from the ground up to optimize the framework with Flex Hero. Some components were rewritten to be mobile-optimized. The mobile theme, used when the MobileApplication tag is detected, has larger, touch-friendly controls, including for scroll bars.

The ViewNavigator helps in the development and management of screens and offers transition animations. The TabNavigator is used for subnavigation. The ActionBar is used for global navigation and messaging.

Using ActionScript and bitmaps is recommended over MXML and FXG at runtime.

If you like the convenience of components but prefer pure ActionScript development, Keith Peters has created lightweight and easy-to-use components (see http://www.min imalcomps.com/ and http://www.bit-101.com/blog/?p=2979).

 

StageWebView and The Native Browser

StageWebView

WebKit is a layout engine that browsers use to render web pages and to support interactivity and navigation history. Developed by Apple in 2002 and open sourced in 2005, WebKit is the default browser built in for Android.

The AIR runtime for the desktop also includes a version of WebKit built in. However, AIR for Android does not include it, and instead leverages the device’s native implementation and gives you access to some of its features via StageWebView.

StageWebView brings the benefits of an Internet browser to your own application. In this chapter, we will briefly discuss accessing the native browser, and then go over what StageWebView has to offer.

The Native Browser

To access the Internet, you need to set the permission for it:

[code]<uses-permission android:name=”android.permission.INTERNET” />[/code]

You can launch the Android native browser from an AIR application using the naviga teToURL method. You pass a URL in the same way you do on AIR for the desktop:

[code]

function onPublicNews():void {
navigateToURL(new URLRequest(“http://www.npr.org”));
}

[/code]

You can also use this method to launch native applications, such as the Android Market, that in turn makes calls to the Internet. The following example opens the Android Market and sets the criteria of applications to display as a URLRequest. Note that the protocol used is market:// instead of http://:

[code]

function onSearchMarket():void {
navigateToURL(new URLRequest(“market://search?q=food”));
}

[/code]

In both cases, your application moves to the background and the native browser becomes the active application.

We need, instead, a solution whereby HTML content can be embedded inside an AIR for Android application. This is what the StageWebView class does.

 

Preparing Video

A codec is software used to encode and decode a digital video signal. Engineers try various solutions to maintain video quality while reducing the amount of data, using state-of-the-art compression algorithm design.

A large portion of your work will comprise preparing and testing various configurations.

Codecs

At the time of this writing, AIR for Android supports codecs for On2 VP6, H.263 (Sorenson Spark), and H.264.

H.264, also called MPEG-4 Part 10 or AVC for Advanced Video Coding, delivers highquality video at lower bit rates than H.263 and On2. It is more complicated to decode, however, and requires native GPU playback or a fast compressor to ensure smooth playback.

H.264 supports the following profiles: Baseline, Extended, Main, and various flavors of High. Test the profiles, as not all of them work with hardware-accelerated media decoding. It appears that only Baseline is using this at the time of this writing.

AAC (Advanced Audio Coding) is the audio codec generally paired with H.264. Nellymoser and Speex are supported, but do not utilize hardware decoding.

MPEG-4 (Moving Picture Experts Group) H.264 is an industry-standard video compression format. It refers to the container format, which can contain several tracks. The file synchronizes and interleaves the data. In addition to video and audio, the container includes metadata that can store information such as subtitles. It is possible to contain more than one video track, but AIR only recognizes one.

Encoding

You can use Adobe Media Encoder CS5 or a third-party tool such as Sorenson Squeeze or On2 Flix to encode your video.

It is difficult to encode video for every device capacity and display size. Adobe recommends grouping devices into low-end, medium-end, and high-end groups.

If your video is embedded or attached to your application, prepare and provide only one file and use a medium-quality solution to serve all your users. If your video is served over a network, prepare multiple streams.

Gather as much information as possible from the user before selecting the video to play. The criteria are the speed of the network connection and the performance of the device.

Decoding

Containers are wrappers around video and audio tracks holding metadata. MP4 is a common wrapper for the MPEG-4 format and is widely compatible. F4V is Adobe’s own format, which builds on the open MPEG-4 standard media file format and supports H.264/AAC-based content. FLV, Adobe’s original video container file format, supports codecs such as Sorenson Spark and On2 VP6, and can include an alpha channel and additional metadata such as cue points.

Video decoding is a multithreaded operation. H.264 and AAC are decoded using hardware acceleration on mobile devices to improve frame rate and reduce battery consumption. Rendering is still done in the CPU.

Bit Rate

Bit rate is the number of bits dedicated to the video in one second (measured in kilobits per second or kbps). During the encoding process, the encoder varies the number of bits given in various portions of the video based on how complicated they are, while keeping the average as close to the bit rate you set as possible.

Because the average is calculated on the fly and is not always accurate, it is best to select the two-pass mode even though it takes longer. The first pass analyzes the video and records a statistics log; the second pass encodes the video using the log to stay as close to the desired average bit rate as possible.

Use the network connection speed as a guide for your encoding. The recommendation is to use 80% to 90% of the available bandwidth for video/audio combined, and keep the rest for network fluctuations. Try the following H.264/AAC rates as a starting point:

  • WiFi: 500 to 1,000 kbps, audio up to 160 kbps
  • 3G: 350 to 450 kbps, audio up to 128 kbps
  • 2.5G: 100 kbps, audio up to 32 kbps

Frame Rate

Reduce high frame rates whenever possible. Downsampling by an even factor guarantees a better result. For instance, a film at 30 fps can be downsampled to 15 fps; a film at 24 fps can be downsampled to 12 or 18 fps.

Do not use content encoded at a high frame rate and assume that a lower frame rate in AIR will adjust it. It will not.

If your footage was captured at a frame rate greater than 24 fps and you want to keep the existing frame rate, look at reducing other settings such as the bit rate.

If your video is the only moving content in your application, you can use a frame rate as low as 12 fps because the video plays at its native frame rate regardless of the application’s frame rate. A low frame rate
reduces drain on the battery.

Resolution

The pixel resolution is simply the width and height of your video. Never use a video that is larger than the intended display size. Prepare the video at the dimension you need.

High resolution has a greater impact on mobile video playback performance than bit rate. A conservative resolution of 480×360 plays very well; 640×480 is still good. A higher resolution will be challenging on most devices and will result in a poor viewing experience on devices that are not using the GPU for decoding or on devices with a 500 MHz CPU. Resolution recommendations are:

  • WiFi or 3G: 480×320
  • 2.5G: 320×240

In fact, you can often encode smaller and scale up without a noticeable decrease in picture quality. The high PPI on most devices will still display a high-quality video.

Decrease your video size by even divisors of 16. MPEG video encoders work by dividing the video frames into blocks of 16 by 16, called macroblocks. If the dimension does not divide into 16 or close to it, the encoder must do extra work and this may impact the overall encoding target. As an alternate solution, resort to multiples of eight, not four. It is an important practice to achieve maximum compression efficiency.

As for all mobile content, get rid of superfluous content. If necessary, crop the video to a smaller dimension or edit its content, such as trimming a long introduction.

For more information on mobile encoding guidelines, read Adobe’s white paper at http://download.macromedia.com/flashmediaserver/mobile-encoding-android-v2_7.pdf.

Performance

Hardware is improving quickly, but each device’s architecture is a little different. If you want to target the high end of the market, you can add such comments when submitting your applications to the Android Market.

In addition to your encoding settings, there are some best practices to obey for optimal video playback. They are all simple to apply:

  • Do not put anything on top of or behind the video, even if it is transparent. This would need to be calculated in the rendering process and would negatively affect video playback.
  • Make sure your video window is placed on a full pixel (no half-pixel boundaries).
  • Do not use bitmap caching on the video or any other objects on the stage. Do not use filters such as drop shadows or pixel benders. Do not skew or rotate the video. Do not use color transformation or objects with alpha.
  • Do not show more than one video at the same time.
  • Stop all other processes unless they are absolutely necessary. If you use a progress bar, only call for progress update using a timer every second, not on the enter frame event.

Publish to Android Installer

Now that you have created your new application, it is time to publish it to an Android installer file, which is an archive file with an .apk extension. Flash Builder provides all of the tools to accomplish this task.

To demonstrate how to compile an application to an Android installer, let’s walk through this process with the following steps:

  1. First, click on File→Export within Flash Builder’s main menu (see Figure 7-1).
  2. Next, select Flash Builder→Release Build (see Figure 7-2).
  3. Within the Export Release Build window, select the Project and Application that you would like to compile (see Figure 7-3).
  4. If you already have a certificate compiled, select that certificate, enter its password, and click the Finish button to compile the Android installer file (.apk). If you do not yet have a certificate, click the Create button (see Figure 7-4).

    To create a new certificate, complete the Create Self-Signed Digital Certificate form and click on the OK button (see Figure 7-5).

  5. To compile the Android installer file (.apk), click on the Finish button (see Figure 7-6).

Congratulations: you have just compiled your first Android application. To publish your new application to the Android Market, just visit https://market.android.com/publish.

Selecting File→Export

Selecting Flash Builder→Release Build

The Export Release Build screen

Selecting or creating a certificate

 

Creating a new certificate

Completing the export

Monetizing Your Application

Before you submit an application, you should become acquainted with other applications already on the Android Market. Visit the AppBrain website (http://www.appbrain.com/apps/) or the Android Market website  (https://market.android.com) to see the current applications.

For reference, the website at http://www.appbrain.com/apps/popular/adobe-air/ keeps track of the applications developed using AIR.

Paid Applications

Setting up a merchant account with Google Checkout requires that you provide banking and tax information. You only need it for the applications you charge money for. Google’s transaction fee is 30% of the price of your application. The arguments for using the Android Market are security, efficiency, and exposure.

It is up to you to decide whether to charge for your application. Your history is public and available to consumers, so charging a fair price is a good long-term business practice.

Unlike Apple and the Apple Store, Google doesn’t force you to use the Android Market as a distribution channel. Instead, you can place your application on your web server of choice. Your server MIME type needs to be edited, however. The MIME media type for .apk files is application/vnd.android/package-archive.

To install an application on a device via a non-Android Market source, select Settings→ Applications→Unknown Sources. Unless the application is properly documented, this may reduce your audience.

Mobile Ads

If you want to earn money from your work, you can offer your application for free but receive revenues from embedded advertisements. Read Arron La’s story on the revenue he made from his Advanced Task Manager application, at http://arronla.com/2010/08/android-revenue-advanced-task-manager/.

The advertisement displayed in your application is one image with a clickable URL. Here is a short list of some mobile advertising companies:

  • AdMob (http://AdMob.com)
  • Smaato (http://www.smaato.com)
  • Google (http://www.google.com/mobileads/publisher_home.html)

You must subscribe to get an application ID. At runtime, your application makes a request to receive advertisement information. Indicate the ad’s format (XML is best) and dimensions. Some providers allow you to specify geolocation, age, or gender for targeted ads.

All providers give you an option to test your application with dummy ads before it goes live. Always put the advertisement code in a try catch block. You do not want your application to stop functioning because the provider server is down or sends bad data.

At the time of this writing, mobile advertising providers do not offer an AS3 SDK. You need to download the AS2 version and rewrite it for your purposes. Making straight calls in the standalone application does not seem to provide ad impressions. Instead, use the StageWebView API, which allows you to open a web page within your AIR application to simulate the browser experience.

Publishing an Application on the Android Market

An AIR application is packaged as a standard Android application. Therefore, you can distribute it via the Android Market or via another website of your choice.

To publish your application, go to the Developer Console page at http://market.android.com/publish/Home and click on the Upload Application button. Figure 4-2 shows the necessary steps to submit an application.

Uploading Assets

Select “Upload assets” to upload the APK file. At the time of this writing, the maximum allowed size for this file is 50 MB. You can also upload at least two screenshots at 320×480, 480×854, or 480×800; one high-resolution, 512×512 icon; one promotional graphic at 180×120; a feature graphic at 1,024×500; and the URL to an optional promotional video (must be YouTube).

Unless you select the Marketing Opt-Out button, Google has the right to promote your application in the Android Market or other Google-owned properties.

Listing Details

Upon selecting “Listing details,” you can enter the title, a description, some promotional text, the type, and the category of your application. The default language is

Steps to upload an application to the Android Market

English, but you can choose additional languages. As of November 2010, applications need to have a content rating of All, Pre-Teen, Teen, or Mature, as per the Android content policy (see http://www.android.com/us/developer-content-policy.html).

Publishing Options

The Android Market Licensing Service is a protection option to prevent users from copying an application from a device. At runtime, it queries the Android Market to obtain the user’s licensing status. The License Verification Library (LVL) is a component of the Android SDK. It does increase the file size, so choose it only if you are selling your application.

Distributing Applications via Adobe InMarket

Adobe offers a service called InMarket that handles distribution of AIR applications, including credit card processing, hosting, and marketing. You receive 70% of the sales revenue. InMarket has an ActionScript license manager that only works within its system. For more information on InMarket, go to http://www.adobe.com/products/inmarket/ or http://www.webkitchen.be/2010/12/02/inmarket-monetizing-your-apps-made-easy/.

Publishing for the Amazon Market

In March 2011, Amazon opened Appstore for Android, which offers Android games and applications as well as Free Amazon applications.

Note that the Amazon store does not do any filtering, so in your application description, clearly indicate the requirement for at least Android 2.2 and an ARMv7-A processor.

To make your application compatible with this Appstore, you must build an APK specifically for it (build a separate one for the Android market). You must use only AIR 2.6 and up, so that you can overwrite the runtime download URI. Adobe and Amazon are working on a more practical solution. Flash Professional CS5.5 offers a pull-down menu: go to AIR for Android settings→Deployment to target the Google Android Market or the Amazon Appstore.

For more information, read http://blogs.adobe.com/cantrell/archives/2011/03/air-2-6-applications-and-the-amazon-appstore-for-android.html.

Registering As an Android Developer

To submit your application to the Android Market, you must have or create a Google account and sign up as an Android developer. You also must pay a one-time registration fee of $25 (see https://market.android.com/publish/signup).

You should read the Android Market Developer Distribution Agreement (http://www.android.com/us/developer-distribution-agreement.html) as well as the content policy which determines what content is allowed (http://www.android.com/market/terms/developer-content-policy.html).

If you are going to sell applications through the Android Market, you need to set up a merchant account with Google Checkout.

Versioning

Versioning gives you the opportunity to submit fixes and updates to your application. A version number consists of three digits separated by dots, as in 1.0.0, referred to as major.minor.build. Set the version number in Flash Professional in the
Settings window. In Flash Builder, open the application descriptor and change the version number in the XML.

For debugging purposes, you can check the version number at runtime from the appli cationDescriptor of the NativeApplication.nativeApplication that is an XML object:

import flash.desktop.NativeApplication;
var applicationDescription:XML =
NativeApplication.nativeApplication.applicationDescriptor;
var ns:Namespace = applicationDescription.namespace();
// http://ns.adobe.com/air/application/2.6
var currentVersion:String = applicationDescription.ns::versionNumber;
// 1.0.0

The update to an application appears on the Android Market quickly.

As mentioned earlier in this chapter, the update can be accomplished in two ways. You can specify your preference in the application descriptor, or the user can specify it manually. The following tag implies that the update is handled by the user upon doubleclicking:

<customUpdateUI>false</customUpdateUI>

If the user installs an update of your application, previously saved data is preserved.

Signing Your Application with a Certificate

All applications must be signed before being updated to the Android Market. This enables consumers to identify and establish trust with a developer. The developer signs the certificate using a private key. The private key is different from the one you used during development. Typically, a key generally using ADT is only good for five years.

To create a suitable key in Flash Professional, go to File→AIR Android settings→Deployment→ Certificate and fill out every field. The publisher name will appear in the Android Market as you enter it. As before, make a note of the password, since you will need it when you compile your application. Choose Type 2048-RSA, Google’s recommended type.

The certificate must be valid for 25 years. The system only checks the certificate’s expiration date upon installation. If the certificate expires afterward, the application will continue working.

To create a suitable key using AIR ADT and the command line, use the following code, making sure to put your name and country in quotes:

AIR-sdk-path/bin/adt -certificate -cn “FirstName LastName” -c “US”
-validityPeriod 25 2048-RSA myCertificate.p12 myPassword

More information on this is available on the Android developer website, at http://developer.android.com/guide/publishing/app-signing.html.

When/if you later upgrade your application, you must use the same certificate, so keep it in a safe place.

 

Create a Flex Mobile Project

This section will walk you through building your first AIR on Android application using Adobe Flash Builder 4.5. If you don’t have Flash Builder 4.5, you can get a trial version from Adobe at http://www.adobe.com/products/flashbuilder/.

Now that you have Flash Builder 4.5 installed, open it, and let’s get started.

Create a Flex Mobile Project

Create a new Flex Mobile Project by choosing File→New→Flex Mobile Project, as shown in Figure 1-1.

Creating a Flex Mobile Project

This will open the New Flex Mobile Project wizard, which will walk you through the rest of the project creation process. The first screen you are presented with will allow you to set the project name, location, and Flex SDK. Enter the name HelloWorld as the project name, and leave the other settings on their defaults. Click Next, as shown in Figure 1-2.

Establishing a project name and location

The second screen in the new project wizard is where you can select settings specific to the target platform. Unless you have installed a plug-in to add additional platforms, you will only have one option—Google Android, which is already selected as the target platform. Google Android gives you the option of three different application types, which are Blank, View-Based Application, or Tabbed Application. For this first project, please select View-Based Application, as shown in Figure 1-3, and leave the other settings on their defaults.

Next, click on the Permissions tab. Within this tab, you will be able to select the permissions that your application will need in order to interact with the native Android

Selecting an application template

APIs. Please be sure to only select the permissions that apply to your application, as once your application is uploaded to the Android Market, these permissions will be used to filter the devices that will be able to install your application. For example, if you select Camera as a required permission and your application doesn’t actually use a camera, any Android device that doesn’t have a camera will never be able to install your application. For the purposes of this exercise, leave only the INTERNET permission selected, as shown in Figure 1-4. Click Next.

Setting Android permissions

The next screen allows for the configuration of an application server and output folder. For this project we will not be using an application server, so leave it set to None/Other, and click Next as shown in Figure 1-5.

The Server Settings screen

The last screen that you will see in the wizard is the Build Paths screen, where you will be able to set your Application ID. This setting is very important, as Google uses this to identify your application in the Android Market. To ensure that your application has a unique identifier, the reverse domain naming convention works best. Figure 1-6 shows the value of com.domain.mobile.HelloWorld as the application ID. By replacing the word domain with a domain that you own, you can ensure that your application ID is unique. Complete this step and click Finish.

Flash Builder will now create your new project, and by default, HelloWorldHome- View.mxml will be created and opened in the workspace along with the Hello- World.mxml main application file. This is shown in Figure 1-7.

Adding an Application IDA new project has been created

Let’s update the contents of HelloWorldHomeView.mxml by adding a Label:

<?xml version=”1.0″ encoding=”utf-8″?>
<s:View xmlns:fx=”http://ns.adobe.com/mxml/2009″
xmlns:s=”library://ns.adobe.com/flex/spark” title=”HomeView”>
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>
<s:Label text=”Hello World” fontSize=”24″
horizontalCenter=”0″ verticalCenter=”0″/>
</s:View>

Now we can run the application. To do this, right-click on the HelloWorld.mxml file within the Package Explorer and select Run As→Mobile Application, as shown in Figure 1-8. Since this is our first time running this application, the Run Configurations window will open. To run this using the Flash builder emulator, select “On desktop” as the Launch method and select a device from the drop-down menu, as shown in Figure 1-9.

Running an application on a mobile device

Now click Apply, and then click Run—you will see the Hello World application launch within the desktop simulator or on the device. Figure 1-10 shows Hello World running on a device.

Congratulations: you have just created your first AIR on Android application with Adobe Flex 4.5.

The Run Configurations window

The Hello World application in action