Accessibility

Tips for Using Macromedia Flash 4 ActionScript for Flash Lite 1.1 Development

Bill Perry

Macromedia

With Macromedia Flash Lite 1.1, mobile phone consumers can enjoy multimedia-rich content on mobile phones—taking their favorite games, cartoons, or applications with them wherever they go. Mobile operators and content providers can distribute more and more engaging applications, created by Flash developers.

However, there's one important thing developers need to remember: Flash Lite 1.1 content requires the use of Flash 4 ActionScript. Using this limited set of ActionScript keeps the file size and processor hit small for mobile phone platforms.

So what does this mean? If you never used Flash 4 and started only with Flash 5 or a later version, you haven't been able to enjoy the limited aspects of that early ActionScript. In the Flash 4 days, ActionScript wasn't as robust as it is today; it offered only limited programming capabilities. Today you can develop web and desktop content using all of the rich features of Flash MX 2004 and ActionScript 2.0.

In this article I discuss in detail some of the common Flash 4 ActionScript syntax that can be used for Flash Lite 1.1 development in addition to some of the new Flash Lite 1.1 ActionScript commands. I also talk briefly about testing Flash Lite 1.1 content in Flash MX Professional 2004 and describe the various warning and error messages you might see.

Requirements

Flash MX Professional 2004

Macromedia Flash Lite 1.1 Content Development Kit

Level of expertise required:

Some familiarity with creating Flash content for various platforms.

Sample files:


Flash Lite 1.1 Publishing Profile

Most of you know that Flash Lite 1.1 is the latest profile for creating and viewing Flash content on mobile phones. While developing within Flash MX Professional 2004, you can easily create Flash applications for supported handsets by using the Flash Lite 1.1 publishing settings. Be sure to check out the Mobile & Devices Developer Center for the latest list of supported handsets.

There are several good articles already written discussing Flash Lite 1.1 and I recommend that you take a look at them. You can find them on the Flash Lite developer resource page.

Included in the Macromedia Flash MX Professional 2004 7.2 updater is the Flash Lite 1.1 publishing profile (see Figure 1). Once you install the updater, you can publish Flash Lite 1.1–compatible SWF files. This is important if you're going to use any of the Flash Lite 1.1 ActionScript commands, such as code that calls out to specific device capabilities.

Flash Lite 1.1 publish settings

Figure 1. Flash Lite 1.1 publish settings

ActionScript in Flash Lite 1.1

As with any Flash application, chances are that you'll be using some amount of ActionScript in your content to build in interactivity or control certain behaviors. Because ActionScript for Flash Lite 1.1 is based on the Flash 4 ActionScript code base, there are certain limitations to be aware of when developing content.

Differences in Flash 4 ActionScript

In general, Flash Lite 1.1 adheres to Flash 4 ActionScript notation, but it also uses some Flash 5 notation. Being able to understand when and where you have to use Flash 4 ActionScript is critical when developing applications. Because Flash Lite 1.1 uses Flash 4 ActionScript, you have to know how to refer to Timelines and variables using the slash and colon syntax.

Timelines

To specify a path to a Timeline, use slash syntax (/) combined with dots (..) to build the path reference. You can also use _level0 or _root from Flash 5 notation.

Example 1: Targeting the movie clip cards from the main Timeline

tellTarget("/box/cards")
tellTarget("_level0/box/cards")

Example 2: Targeting the main Timeline from a movie clip cards

tellTarget("../../cards")
tellTarget("_root")

Example 3: Referring to the parent movie clip of cards

tellTarget("../cards")
tellTarget("../cards")

Variables

To specify a variable on a Timeline, use slash syntax (/) combined with dots (..) and colons (:). You can also use the Flash 5 dot notation.

Example 1: Variable car on the main Timeline

/:car
_root.car

Example 2: Variable car in a movie clip instance that resides on the main Timeline

/mc1/mc2/:car
_root.mc1.mc2.car

Example 3: Variable car in a movie clip instance that resides on the current Timeline

mc2/:car
mc2.car

Emulating Arrays

Arrays are very useful for creating and manipulating ordered lists of information, usually variables and values. Unfortunately Flash Lite 1.1 does not support the array() constructor, so you must emulate the creation of an array to reference throughout the application. This is referred to as a pseudo-array.

For example, let's say you created the following ActionScript variables:

color_1 = "orange";
color_2 = "green";
color_3 = "blue";
color_4 = "red";

To dynamically access the elements in this pseudo-array, you could use the following ActionScript code:

for (i = 1; i <=4; i++) {
     trace (eval ("color_" add i));
}

Using Timeline-Based Loops for Code

You can use Timeline-based loops for executing a block of code repeatedly, which can be useful for creating movement or acting as a timer. For example, if you wanted to move a movie clip from the top of the Stage to the bottom, you could use a simple motion tween or you could do it with ActionScript.

With ActionScript it would look something like this:

// code on frame 10
for (i = 0; i < 30; i++)
     headline_mc._y += 5;
}
// code on frame 11
gotoAndPlay(10);

Using the add Operator Instead of the & Operator

Whenever you want to concatenate variables or text strings, you must use the add operator instead of the & operator. Because most developers are not familiar with using the add operator, they often experience problems when testing content. This is usually the culprit.

Example 1: Correct way

headline = ("Oil prices reach" add " all time high");

Example 2: Incorrect way

headline = ("Oil prices reach"  & " all time high");

When to Use eq and = =

When using a conditional statement such as if(), you're usually comparing two values to check for equality. The equality operator == is used to compare numbers, strings, and other data types, while the string equality operator eq is used only to compare string values. It's good practice just to use the == operator in conditional statements to avoid having to decide which operator to use.

Example 1: Correct way

if (_root.game == "1"){
	play();
}

Example 2: Incorrect way

if (_root.game eq "1"){
	play();
}

Detecting keyPress Events

Simply put, you can only use keyPress events to check when a user presses a key on the handset. You can only assign these to buttons, so it's a good idea to put all of your keyPress events into one button that's offstage to help organize your code.

Example:

on (keyPress "<Enter>") {
	gotoAndPlay("menu");
}

Here's a complete list of all of the supported keyPress events:

No Movie Clip Events

Movie clip events—such as onEnterFrame(), onKeyDown(), onUnload(), and others—are not supported by Flash Lite 1.1, and you should not use them. If you do, you'll get warning messages in the authoring environment when you run a Test Movie command.

No Custom Functions—Use call() Instead

One big drawback to remember is that you cannot use functions in Flash Lite 1.1 content. The workaround is to use the deprecated call() function instead. It's pretty straightforward and easy to use.

Example:

// custom AS code on a frame labeled "buttonAction"

if (_root.object == "help") {
     gotoAndStop("helpSection");
} else if (_root.object == "extras") {
	gotoAndStop("extrasSection");
}

// AS code for help button

on(keyPress "8") {
	_root.object = "help";
	call("buttonAction");
}

Supported ActionScript

For a complete list of all supported Flash Lite 1.1 ActionScript commands, refer to Appendix A in the Macromedia Flash Lite 1.1 Authoring Guidelines.

Flash Lite 1.1 ActionScript Examples

I've put together some sample code and files to help you gain a better understanding of Flash Lite 1.1 development. The sample code and files presented here are meant to give you an idea of how to solve some common problems that you may run into while developing content.

You might be wondering at this point how you can use Flash 4 ActionScript in your Flash Lite 1.1 content. I've selected a few of the most commonly used ActionScript commands and provided some sample code for each instance. These examples give you an idea of how to use a particular command. You should be able to apply the basis of these code examples to your own work.

Common Commands

getProperty()

When you use getProperty(), you can retrieve a value for any of the built-in properties of a movie clip. This is often used in conjunction with the setProperty() function.

Example:

cartoonArea_x = getProperty(cartoonArea, _x);

setProperty()

This allows you to specify one of several properties for a movie clip instance, which is very useful for repositioning objects on the Stage.

Example:

setProperty(cartoonArea, _x, 100);

tellTarget()

Another one of the forgotten ActionScript commands, tellTarget() was the original way of communicating between two movie clips, directing a movie clip either to play, stop, or go to a particular frame. You're going to have to use this often for Flash Lite 1.1 development, so get used to it!

Example:

tellTarget("_level0/headlines/title") {
		gotoAndStop(1);
	}

getURL()

Flash Lite 1.1 supports the getURL()action, which is processed once per frame or per event handler and can only be associated with the following keys: 0–9, *, #, or the Select key. If you have more than one getURL() call in the same statement block, only the first call is executed.

Example: Loading a web page into the mobile phone's browser

getURL("http://mobile.flashdevices.net/");

It's worth mentioning that certain handsets require a keyEvent to process getURL() calls. Basically this means the user needs to press a key on the handset to initiate the getURL() call; it can't occur as a frame event.

In addition, these calls will only be processed once per frame or per event handler. Keep this in mind as you develop your content.

Refer to the CDK for the platform you're developing for to get additional information.

eval()

This function lets you dynamically generate variables within your application.

Example: Defining two variables and then creating a new variable based on those two variables

num = 2;
team2 = "Red Sox";
baseballTeam = eval("team" add num));  
// result is "Red Sox"

loadVariables(), loadVariablesNum()

As with the desktop version of Macromedia Flash Player, you can use loadVariables() and loadVariablesNum() to load in data from a web server using the data connection on a mobile phone. By using these functions, you can update Flash content that resides on a mobile phone and make it dynamic.

Example 1: Loading variables into a specific movie clip using the loadVariables()function

loadVariables("http://www.flashdevices.net/data/scores.txt", "scores_mc");

Example 2: Loading variables into a specific level using the loadVariablesNum()function

loadVariablesNum("http://www.flashdevices.net/data/news.txt", 5);

Again, the loadMovie() calls have the same exceptions and rules as I mentioned above in the getURL() section.

loadMovie(), loadMovieNum()

You can load external SWF files from a web server into a SWF file that already resides on a user's handset which these functions. One possible use would be to provide a new image to the user that would be displayed in the original application.

Example 1: Loading a new SWF file into a specific movie clip using the loadMovie()function

loadMovie("http://www.flashdevices.net/data/dailyPhoto.swf", "mainScreen_mc");

Example 2: Loading a new SWF file into a specific level using the loadMovieNum()function

loadMovieNum("http://www.flashdevices.net/data/dailyPhoto.swf", 10);

Again, the loadMovie() calls have the same exceptions and rules as I mentioned above in the getURL() section.

on(keyPress)

One of the most basic ActionScript commands, this is used to detect when a user presses a key on the handset.

Example:

on (keyPress "<PageDown>") {
	FSCommand2 ("Quit");
}

URL Encoding

Two commands, Escape and Unescape, are available to encode and unencode strings to and from formats that are safe for network transfer as they pass between servers and mobile phones.

Escape

This function encodes an arbitrary string into a format that is safe for network transfer. It replaces all characters that are not alphanumeric with a hexadecimal escape sequence (%xx or %xx%xx in the case of double-byte characters). It returns the encoded string in a variable that is passed into the SWF file by name. This function is executed immediately upon invocation.

Here is the syntax:

status = FSCommand2( "Escape", original, encoded )

where original is the string to be encoded into a format safe for URLs and encoded is the resulting encoded string.

Example:

original_string = "hello, how are you?";
status = fscommand2("Escape", original_string, "encoded_string");

Unescape

This function decodes an arbitrary encoded string that is safe for network transfer into its normal form. All characters that are in hexadecimal format—that is, a percent character (%) followed by two hexadecimal digits—are converted into their decoded form. It returns the decoded string in a variable that is passed in by name. This function is executed immediately upon invocation.

Here is the syntax:

status = FSCommand2( "Unescape", original, encoded )

where original is the string to be decoded from a format safe for network transfer and encoded is the resulting decoded string.

Example:

original_string2 = "Hello%7B%5BWorld%5D%7D";
status = fscommand2("Unescape", original_string2, "normal_string");

Controlling Text Boxes

scroll

You can use the scroll property to retrieve and set the contents of a text box. When you retrieve the scroll property of a text box, it indicates the number of the line currently displayed as the first line in the text box's viewable area. When you set the scroll property to a specific value, it scrolls the text field, making the specified line number the top line in the field's viewable region.

Example:

on (release) {
	mainText.scroll = mainText.scroll + 1;
}

maxscroll

The maxscroll property returns the largest allowable scroll value for a text field. It represents the number of the last line in a text field that can be used as the top line in its viewable region.

Example:

textBoxMax = mainText.maxscroll

Executing Commands with FSCommand2()

The FSCommand2() function is a new ActionScript function that is supported in Flash Lite 1.1 but not yet supported in the standard desktop version of Flash Player. It provides similar functionality to the FSCommand() function, but its main benefits are that it:

An example of an FSCommand2() function would be the GetBatteryLevel() command, which retrieves the current battery level of the handset as a numeric value.

Example:

batteryLevel = FSCommand2( "GetBatteryLevel" )

Controlling Movie Clips

Here are some examples of how to control movie clips in Flash Lite 1.1 using tellTarget:

// telling a movie clip to go to and play a label
tellTarget("../photoArea"){
    gotoAndPlay("begin");
}

// telling a movie clip to go to and stop at a frame
tellTarget("/nameList"){
    gotoAndStop(1);
}

// telling a movie clip to load a SWF file from a web server
tellTarget("../photoArea"){
     loadMovie("http://www.flashdevices.net/data/pen.swf", "/icon_mc");
}

Stopping Sounds

If you have audio playing in your Flash application, and you want to stop all sounds that are playing, just use the following ActionScript code inside a button or on a frame event:

// stopping all sounds
stopAllSounds();

Opening a Web Page

If you want your application to open a web page on the user's handset, you can do this by using the following ActionScript code:

// opening up a web page
on(keyPress"<Enter>"){
    getURL("http://mobile.flashdevices.net/");
}

Note: This uses the default browser on the user's handset.

Simulating Video

Although it is not possible to play back video within Flash Lite content, you can simulate this effect by using some ingenuity. Basically you need to grab any number of frames from the video using whatever video editing tool you have available, tweak them using your favorite image editing program (like Macromedia Fireworks), and then import them into your FLA file. Create a movie clip that contains the imported images and then use this movie clip within your application.

Take a look at the example file FlashLite_fake_video.fla for more information (see Figure 2). Keep in mind that there's a limited amount of memory available to supported handsets, so try to keep the image sizes small to avoid any memory issues with the Flash Lite 1.1 player.

Image from the Fake Video example file

Figure 2. Image from the Fake Video sample file

Detecting File Download Completion

Being able to load variables and SWF files into your Flash application is pretty cool, but how do you know when the file you requested has been completely downloaded, let alone successfully downloaded?

This is a common question for developers and is especially important when developing content for mobile phones. Here's my solution to the problem: Use the FSCommand2 ("GetNetworkRequestStatus") command, a loop, and a conditional statement.

Interested in seeing how it works? Take a look at the FL_detect_completion.fla file located in the examples folder (see Figure 3). The FLA file has comments within the ActionScript code to help explain what's going on.

Download status image from the FL_detect_completion.fla example file

Figure 3. Download status image from the FL_detect_completion.fla sample file

Platform Capabilities

There are certain platform capabilities and variables available to Flash Lite 1.1 that you can use to test what functions a specific handset platform supports. Why would you want to know this? Well, if you want to create an application that lets a user dial a telephone number from within a Flash application, for example, you first need to determine whether or not your target handset platform is capable of doing so.

There are two ways of determining this. The first is to copy the capabilities.swf file—included in the Macromedia Flash Lite 1.1 CDK sample files—to your handset. When you run it you get a listing of all the Flash Lite 1.1 platform capabilities. The ones that the handset supports show a result of "1". The other way is to add only the platform capabilities you're interested in using into your FLA file and test it. Either way you get the same results.

Flash Lite 1.1 Interface Elements

As I mentioned in my previous article, Best Practices for Developing Flash Lite 1.1 Content, in the Macromedia Flash Lite 1.1 CDK there are eight different types of prebuilt interface elements in four different colors (blue, green, orange, and silver), which you can use and customize while developing your content (see Figure 4).

Various types of ready-to-use Flash Lite 1.1 interface elements
  • Actions menu
  • Button
  • Check box
  • Drop-down menu
  • Numeric stepper
  • Radio button
  • Scroll bar
  • Text field

Figure 4. Various types of ready-to-use Flash Lite 1.1 interface elements

Using these interface elements in your project is simple:

  1. Locate the "Interface elements" folder within the Flash Lite 1.1 CDK folder and open up the FLA file you want to use.
  2. Select the interface element on the Stage and copy it.
  3. Paste it into your FLA file.
  4. Modify any ActionScript for that particular element inside your FLA file.
  5. Test and modify if necessary.

When modifying the ActionScript for a particular interface element, be sure to check out the original FLA file to see if there are any comments on what you can modify.

Testing Your Flash Lite 1.1 Application

When Macromedia created the Flash Lite 1.1 profile for publishing SWF files, they also included a comprehensive set of warning and error messages to help developers thoroughly test their applications both in the authoring environment and on handsets.

Testing in the Authoring Environment

There is no device emulator for testing Flash Lite content inside the authoring environment that mimics a phone's actual processor speed; however, you can test your user interaction and ActionScript commands by using the Test Movie feature of Flash MX Professional 2004 (see Figure 5).

Testing your Flash Lite 1.1 content inside the authoring environment

Figure 5. Testing your Flash Lite 1.1 content inside the authoring environment

By testing the functionality of your application this way, you are able to catch any problems before copying the SWF file to your handset for further testing. It's much easier to make changes and retest your movie in the desktop environment rather than publish a new SWF file, copy it to your handset, and test it there. Testing in the authoring environment saves a lot of development time, and as you begin to create content you'll notice how much time you save. Thanks, Macromedia!

To ensure that you properly test the key inputs for your SWF file, make sure you have the Disable Keyboard Shortcuts option checked (Control > Disable Keyboard Shortcuts). Often if you test your content by using the arrow keys or numeric keys (0–9) and it does not perform correctly, it may be because the Disable Keyboard Shortcuts option is not checked.

Warning and Error Messages in the Authoring Environment

When you test your content inside the authoring environment (using Test Movie), and if you have your publish settings set to Flash Lite 1.1, the Output panel displays any warning or error messages that may pertain to your content (see Figure 6).

Output panel display while testing Flash Lite 1.1 content

Figure 6. Output panel display while testing Flash Lite 1.1 content

One nice thing about the warning and error messages in the Flash authoring tool is that you can customize what messages appear for the specific handset platform you're developing for. By default the Flash Lite 1.1 configuration file is set to show all warning and error messages. You can change the configuration file to suit your own testing purposes. Refer to the "Using the Optional Configuration File" section on page 52 of the Macromedia Flash Lite 1.1 Authoring Guidelines for detailed information.

Because there are over 100 warning and error messages, it doesn't make sense for me to list them all here—besides, you wouldn't want to read them all right now anyway. Instead, I encourage you to take a look at Appendix C in the Macromedia Flash Lite 1.1 Authoring Guidelines for the complete list, along with an explanation of each message.

Flash Lite 1.1 Player Error Messages

Once you get your SWF files copied over to your handset, open and view your file using the Flash Lite 1.1 player. As you begin to develop and test content, you may notice error messages (see Figure 7). These are nothing to get alarmed about; they are simply a way for the Flash Lite 1.1 player to say "Hey, something's not right with your content." It's worth noting that these error messages show up on Series 60 and UIQ handsets but may not appear on other handsets that support Flash Lite 1.1.

An example of the error message ”Problem with content: 6,” which indicates a SWF file that has a JPG image that is too large

Figure 7. Example of the error message "Problem with content: 6," which indicates a SWF file with a too-large JPEG

Here's a complete list of the "Problem with content: number" messages you may encounter, listed by error number:

  1. Out of memory
  2. Stack limit reached
  3. Corrupt SWF data
  4. ActionScript stuck
  5. Infinite AS loop
  6. Bad JPEG data
  7. Bad sound data
  8. Cannot find host
  9. ActionScript error
  10. URL too long

Usually after the Flash Lite 1.1 player prompts you with a message, you need to exit the player, relaunch it, and open the SWF file again.

Where to Go from Here

I hope you have a better idea of Flash 4 ActionScript and how it applies to developing Flash Lite 1.1 content, especially how to test content inside the authoring environment and how to interpret the various warning and error messages.

Use the following resources for more information when developing content:

If you've created a Flash Lite 1.1 application, let me know—I'd love to see it. If you have any questions, feel free to e-mail me—I'll be happy to help you out.

About the author

Bill Perry is in charge of developer relations for mobile and devices at Macromedia and is helping to shape the future of mobile devices using Flash technologies. He interacts and supports developers, content providers, media owners, mobile operators, and handset/device manufacturers from around the world. When he's not busy with work, Bill enjoys cycling and spending time with his wife and friends.