Flash Lite: Graphics for Mobile Devices

Based on Adobe’s Flash technology, Flash Lite is specifically developed for mobile phones and other consumer electronic devices.


June 08, 2007
URL:http://www.drdobbs.com/mobile/flash-lite-graphics-for-mobile-devices/mobile/flash-lite-graphics-for-mobile-devices/199902665

Hartti is a Senior Technology Expert at Forum Nokia. He can be contacted at [email protected].


Flash Lite is a technology specifically developed for mobile phones and other consumer electronic devices. It is based on Adobe's Flash technology, which makes websites livelier.

Contrary to traditional mobile programming languages such as Java ME and C++, Flash Lite application development starts with the content, rather than coding. Although Flash Lite developers do write code to get applications to behave correctly, the graphical approach broadens the potential mobile developer population to include graphical designers and visually oriented people.

Flash applications are interactive movies or animations based on keyframes placed on a timeline. The difference between movies and Flash animations is that Flash apps can jump from one keyframe to another that isn't necessarily adjacent in the timeline. Another difference is that the Flash Lite animations can contain objects, which are animations themselves. Additionally, you can control animation objects from within your program, such as creating new animation objects using object templates.

With Flash Lite, you can create games, connected applications, and utilize mobile phone functions to send SMS or place phone calls. Flash Lite applications can also access device properties, such as battery-level and network connection-level information, which can sometimes be hard to get from, say, Java MIDlets.

A great feature is that the Flash Lite player automatically scales the application to fit the screen size of the device, so you don't need to code a lot of logic to handle that. So, even though an application might have been developed and tested for a screen size of, say, 176×208, the same application can run on phones with screen resolutions of 128×160 or 240×320.

The scaling works surprisingly well. Problems do arise when the screen proportions are completely different from the target screen size, which can cause graphics to not fit the full screen.

In this article, I present a network-connected Flash Lite 1.1 application that receives data from a server using name-value pairs. The sample data I use are baseball statistics, but it could be weather information, news stories, or timetable information. This application requires access to a web server running MySQL and PHP, a mobile phone that supports Flash Lite 1.1 or better (for example, a Nokia S60 3rd Edition device or some of the Series 40 3rd Edition Feature Pack 1 devices), and a Flash development tool (Flash 8 Professional).

Which Flash Lite Version to Target?

There are a number of different versions of Flash Lite. The most widely deployed version on handsets is Flash Lite 1.1. However, Flash Lite 2.x players have started popping up on some handsets. Table 1 lists the differences between Flash Lite 1.1 and 2.

  Flash Lite 1.1 Flash Lite 2
Based on Flash 4 (ActionScript pre-1.0) Flash 7 (ActionScript 2.0)
Support for device video No Yes
Support for data download Yes (text, value-name pairs only) Yes (XML and name-value pairs)
Support for image download Yes (inside a swf-file only) Yes
Support for saving data on the device No Yes
Support for arrays No (workaround available) Yes
Application types Standalone, wallpaper, screen savers (depending on the device) Standalone, wallpaper, screen savers (depending on the device)

Table 1: Flash Lite 1.1 versus 2.

Flash Lite players running on mobile devices are backward compatible: A Flash Lite 2 player can execute Flash Lite 1.1 animations, but not vice versa. Hence, if you want to address the biggest potential market, you have to use Flash Lite 1 as the development target. Unfortunately, Flash Lite 1.1 is based on older technology, which is missing key features for effective application development. This means that, for some applications, it is better to go with Flash Lite 2.

A big difference is support for external data downloading. XML support is only available for Flash Lite 2 applications. The only way to retrieve text data from a server in Flash Lite 1.1 is to use name-value pairs. If you cannot transcode your structured data to simple flat file, you might need to use Flash Lite 2.

But using name-value pairs isn't that bad. For instance, fewer bytes are transmitted via name-value pairs than with, say, XML formats that add extra bytes in messages. Since users in some countries pay for each byte transmitted over the network, it is a good idea to limit the amount of transmitted data.

Another difference between Flash Lite 1.1 and 2 is support for array data objects. Flash Lite 1.1 is based on Flash 4. Since there is no support for arrays in Flash 4, Flash Lite 1.1 does not support arrays either. Arrays are supported on Flash Lite 2.

However, you can emulate arrays in Flash Lite 1.1 using the eval() function, which takes a name of a variable as a parameter and returns the contents of that variable. For example, if the variables name1,name2, ..., name10 contain names of baseball players, Listing One displays the names of the players.

for (i=1; i<=10; i++) {
    playerName = eval("name" add i);
    trace(playerName);
}
Listing One

Preparing the Data Service

Unless you use an existing data service, you need to set up a server on the Internet to provide data to your application.

Again, the simplest solution is to send a text file composed of name-value pairs as a response to the HTTP request coming from the Flash Lite application. The file can be a static file, but you can create more compelling applications using data from, say, a MySQL database. The format for this text file is "<name>=<value>&" where the ampersand (&) separates one name-value pair from the next pair.

When a Flash Lite application receives a response containing a list of name-value pairs, it stores that data by creating variables called "name" containing the "value" as their value. The Flash Lite LoadVariables() method lets you point out the object where the data is to be stored. This loose encapsulation helps keep the application manageable.

In my example, all that's needed on the server side is a PHP script, which retrieves the requested data from the SQL server, then properly formats it. Listing Two publishes yearly top-five salary and homerun lists as name-value pairs from a SQL server. The data in this example is imported from www.baseball-databank.org. The database is huge, but we are using just a small subset of the information in it.

<?php
// create the SQL query based on query type and the year
// there is a hardcoded 5 row limit (returning only top 5)
switch ($_GET["query"])
{
    case "homeruns":
        $sqlquery = "SELECT nameFirst, nameLast, 
            HR AS value FROM master, 
               batting WHERE master.playerID=batting.playerID 
                  AND batting.yearID= '" . $_GET["year"] . "'
                      ORDER BY HR DESC LIMIT 0,5";
        break;
    case "salaries":
        $sqlquery = "SELECT nameFirst, nameLast, ROUND(salary) AS
            value FROM master, salaries 
               WHERE master.playerID=salaries.playerID 
                  AND salaries.yearID= '" . $_GET["year"] . "' 
                      ORDER BY salary DESC LIMIT 0,5";
        break;
    default:
        die("Incorrect query requested");
}
// make the SQL connection ready
mysql_connect("<your mysql server address here>", 
  "<your mysql username here", "<your mysql password here>") or 
    die("Could not connect to database");
mysql_select_db("baseball") or
    die("Could not select database");
// make the SQL query
$result = mysql_query($sqlquery) or
    die("Could not complete query\n&noData=true&\n&loaded=true&");
// print out the resulting rows as name-value pairs, 
// limited with &-characters
$i = 1;
while ($row = mysql_fetch_array($result))
{
    echo "&name$i=" , $row["nameFirst"] , " " ,  $row["nameLast"] , 
         "&\n";
    echo "&value$i=" , $row["value"] , "&\n";
    $i++;    
}
// turn on the noData flag if result set was empty
if ($i == 1) 
    echo "&noData=true&\n";
// turn on the flag indicating that all data has been loaded
echo "&loaded=true&";
?>
Listing Two

The script adds one additional variable loaded at the end of the data. Since loading data over a cellular network can take a few seconds, the client should show a "loading data" page to the user. The solution here is to add an extra variable to the end of the data file, which is also updated on the client side. When this variable is set, the client knows all data has been received. If there are no results for the query, a noData variable is sent to the client, so that an empty results page is not shown to users.

Getting Started with Client Applications

The development tool of choice for Flash Lite applications is Flash 8 Professional, which comes with built-in Flash Lite 1.1 development tools. You can download a free, fully functional 30-day trial of Flash 8 Professional from Adobe (www.adobe .com). Support for Flash Lite 2, as well as new device emulators, is also available as free downloads from Adobe. If you are using Flash MX Professional 2004 for general Flash development, you can also generate mobile applications with that. However, you need to first install some DLLs and other necessary files manually.

As Figure 1 shows, the main Flash 8 window is different from other tools or IDEs. The timeline on the top of the screen shows the layers used in the application and points out the keyframe currently being worked on at the stage. On the right side, there is a collection of panels, including the library for storing objects. The property inspector is at the bottom of the screen.

[Click image to view at full size]

Figure 1: Main Flash 8 window.

To get started with development, start a new project by clicking the Global Phones link under Create from Template in the Flash 8 start-up screen. In the following dialog window, select Flash Lite 1-1 - Symbian Series 60, and then press OK.

Save the resulting blank application with a descriptive name (like "baseball.fla"). The .fla file format is used in the Flash Lite authoring phase. When the application is published (compiled) for installation on a real phone, the resulting file format is .swf.

Testing the Application

You can use the built-in Flash Lite phone simulators to test the application at any time during development. I recommend testing applications regularly. Just select Test Movie from the Control menu (or Ctrl-Enter).

When the device player is launched, this message is displayed on the Output console:

FTPS030: FSCommand2 FullScreen command not supported
in the emulator, please test it on the device

This message appears because the authoring tool automatically inserts the following command in the first frame of the application. This command is only executed on real devices; emulators don't support it:

fscommand2("FullScreen", true);

At this point, you can edit the phone list you plan to test your application on by selecting Device Settings in the Test Device pull-down menu. This brings up the Device Settings dialog, which you can use to select phones from the list on the left side (Available Devices) and add them in the emulated devices list (Test Devices) on the right.

Also at this point, you can download and install the new device profiles from Adobe by following the link "Check for new devices" in the bottom-left corner of the dialog screen.

Creating Application Structures

Figure 2 illustrates the structure for the baseball application. After opening the application, users land on a selection page, where they can edit the year for which the statistics are retrieved. They then initiate the network data retrieval by selecting either the Top 5 Homeruns or Top 5 Salaries buttons. There is also an Exit button.

[Click image to view at full size]

Figure 2: Application structure.

After the data has been retrieved, users are forwarded to a results page, where they can see the resulting players. By pressing the right softkey, users are returned to the selection page. From that page they make a new selection or exit.

The selection page is the first frame of the application. Because it is helpful to keep the Flash applications organized with layers, you should create an additional layer named "Buttons" between the ActionScript and Content layers. If you want a background that's different for different screens, you should create a Background layer in the bottom of the layer stack.

Create three static text items on the Content layer and enter the text (Top 5 Homeruns,...) previously mentioned. Also, create an input text field for getting the year and a static text field as a label for it. In the property inspector, enter statYear in the Var field of the input text field you created—this ties the statVar variable to the contents of the text field.

The next step is to create the selection rectangles for the menu. First, create an invisible button with the command Insert->New Symbol. That button is placed in the Library and the contents (currently nothing) of that object are shown on the Stage. Define a keyframe in the hit state of the button, and define the clickable area of the button by drawing a rectangle in that state. Change the active layer to Buttons and copy this invisible button on top of the three text items. The screen on the stage should look something like Figure 2.

To make the application functional, add Listing Three (a) on the ActionScript layer of frame 1. The three buttons—homeruns, salaries, and exiting the application—should contain Listings Three (b), (c), and (d), respectively. This lets users move the focus with the joystick from one button to another and select the current button with the selection key.

(a)
// this ActionScript sets your  // content to be full screen
fscommand2("FullScreen", true);
statYear = 2006;
stop();

(b)
on (release) {
    target = "homeruns";
    gotoAndPlay("frLoad");
}

(c)
on (release) {
    target = "salaries";
    gotoAndPlay("frLoad");
}

(d)
on (release) {
    fscommand2("Quit");
}
Listing Three

In the main timeline, create keyframes on frames 5, 10, and 15. In the property inspector, name the frames frLoad, homeruns, and salaries, respectively. Go to frame frLoad, place a static text field on the Content layer, and enter "Loading data, please wait..." in the text field. This remains until the data is fully loaded from the server to show populated statistics data pages. To generate a control structure for the waiting screen, create additional keyframes in frames 6 and 7, and name frame 6 wait1.

Next, go to the frame homeruns, and generate the result display on the Content layer. Use a static text field for the title; if you want to show the selected year, create a dynamic text field next to the title. In the property inspector, enter statYear in the Var field. Generate a 5×2 grid using dynamic text fields (you could use borders in these fields), and tie variables to be downloaded from the server to each of these fields. The first row points to variables name1 and value1, and so on. Repeat the steps for frame salaries.

Adding the Final Code

The Flash Lite 1 function call LoadVariables retrieves data from the server. You can use the Help functionality of Flash Professional 8 to view how this function (or any other Flash Lite function) is used. In the Actions panel (below the Stage), click Global Functions, click Browser/Network, right-click LoadVariables, and select View Help from the pop-up menu.

Add Listing Four (a) to the ActionScript layer of frame frLoad. This initializes the necessary variables and starts the data download. Listings Four (b) and (c) go to the ActionScript layers of frame wait1 and frame 7. These two frames are displayed in sequence until the data has been fully downloaded. This lets you create an animation for users to watch while data is being downloaded, and to let them know that the application is still active.

(a)
// initialize and clear the variables
loaded="false";
noData="false";
for (i=1;i<5;i++)
{
    eval("name" add i) = "";
    eval("value" add i) = "";
}
url = "<URL to your PHP-script page>?query=" add target add "&year="
       add statYear;
LoadVariables(url, _root);

(b)
if (loaded eq "true") 
{
    if (noData eq "true")
        gotoAndPlay(1);
    else
       gotoAndStop(target);
}

(c)
gotoAndPlay("wait1");

(d)
fscommand2("SetSoftKeys", "Options", "Back");

(e)
on(keyPress "<PageDown>")
{
    gotoAndPlay(1);
}
Listing Four

Listing Four (d) has to be placed in the ActionScript layer of frames homeruns and salaries. This command lets the system listen when users press softkeys; the application is using the right softkey for returning to the selection page (note the Back-label on the lower right corner of the result screens). However, because this is not enough to process the softkey presses, you need to create a button (you can drag a copy of the btInvisible from the library on the stage) on both of the frames. Place the button outside the display area, which lets the button listen to the key presses although users can't select it. Place Listing Four (e) on the button.

Your application should now be fully functional. Test the movie in the simulator of the IDE, then on a real device. For example, if you have an S60 handset, you can transfer the nettest.swf file to the phone using the File manager of the PC Suite application.

The folders to store the Flash Lite applications vary from phone to phone. On S60 3rd Edition devices you should transfer the file to the /Data/Others folder. On older S60 phones the correct directory is /documents/Flash. With Series 40 phones, you do not need to worry about where to store the file because the phone automatically stores it in the correct folder.

Where To Go From Here

This application demonstrates the development and testing of a Flash Lite application that retrieves text data from a server. You can use fancy graphics to create a more appealing UI that looks less like a series of plain forms. Another addition could be a splash sequence. For example, generate a splash graphics in the first frame of the application and extend that keyframe for a number of frames.

Adding audio-visual items also makes the application more appealing. Sounds would likely play a minor role in this kind of application, although some game-related audio clips would spice up the pages. Flash Lite supports MP3 on some phones. Photos of baseball players would also be nice, although when working with Flash Lite 1.1, you'd need to convert photos to Flash Lite movies, which could then be retrieved from the server using the LoadMovie() function.

Another enhancement is to retrieve more complex statistics. This example only shows a couple of top players for a certain year. You could create an interface that shows the fielding of players for different teams and years using a field diagram. Or you could calculate some advanced player statistics based on the batting information.

If the data to be downloaded to the application is already in XML format (RSS feeds, for example), you could use Flash Lite 2's XML capabilities. While this increases the size of downloadable data and makes the application more costly to users, the XML approach also makes it easier to create more compelling data rich applications. In addition, you could use other Flash Lite 2 features, such as greater control of the animations from ActionScript and MediaPlayback API.

Terms of Service | Privacy Statement | Copyright © 2024 UBM Tech, All rights reserved.