Posts tagged "tips"

ActionScript Tip: Splicing and Slicing

Array.splice() and Array.slice() are 2 powerful functions that you can use to manipulate the content of your List component. If used effectively, you can achieve a List filtering effect without using any other complex filtering techniques.

First off, what happens when you do this:

var myArray1:Array = new Array();
var myArray2:Array = new Array();

//Push an object to Array1
myArray1.push(new String("ALL"));

//Assign Array1 content to Array2
myArray2 = myArray1;

//Push another object to Array1
myArray1.push(new String("Only for Array1"));


Whatever objects you add to myArray1, automatically gets into myArray2 because of the Array assignment. In your application if you want the 2 arrays two share the content initially but not bound together at a later stage, you need to ‘slice’ the Array:

//Do not do this
myArray2 = myArray1;

//Do this to create a copy of myArray1
myArray2 = myArray1.slice(0);


Splicing, is another technique that will allow you to modify the content of the array without creating a copy of it.

//Remove the first element of myArray1 and assign the content to myArray2.
//When you modify myArray1, myArray2 will also change.

myArray2 = myArray1.splice(0,1);


You can follow these Array manipulation techniques in your application to create List components with filters, which will bind different arrays to the list at run time.

Here’s an application I built for the Android market, a simple action items tracking system using associative arrays and filters:

See also:

Design Considerations for Building Mobile Applications

Mobile computing has grown hugely popular over the last several years. The growing capabilities of the mobile phones has meant that the phone has become an appealing and persuasive platform for application developers to build both consumer and enterprise applications. Today, developers have started building applications that are ubiquitous and multiscreen-capable. However, the trick is to build a mobile application that will work on phones having different software and hardware capabilities. How do you achieve this? While you have no control over the phone’s platform segmentation, you can build mobile applications following certain considerations, widely recognized as the ‘best practices’ for building mobile applications.

Here are some design considerations for building mobile applications:

  1. Decide on the application type. It is the high order bit! Do you want to build a native application or a Flash/AIR-based application? Whatever you decide, understand that it is very expensive to rollback this decision. Developing native application has its own benefits and shortcomings. For very trivial application, go native. For complex applications, go Flash.
  2. Don’t worry about the phone’s platform fragmentation. For any open system to proliferate, fragmentation is important. Do not worry if your application does not work well on some devices. Find out other ways to filter out your application from those devices.
  3. Storage. There is no such thing as a 1 TB SD card! Use the phone’s data memory judiciously.
  4. Connection and bandwidth. Understand that the users pay for every byte transmitted and received. Before you open up a data connection or before you start downloading that large piece of data from a service, warn the user.
  5. Tombstoning. Handle system interrupts effectively. When your application is pushed to the background, pause those game timers, disable those animations, and save the state of your application.
  6. Memory usage. Nothing much can go wrong here if you design your application well. Never get overwhelmed by the memory usage statistics reported by the phones. For AIR-based applications, the memory usage may also include the AIR Runtime footprint. Don’t panic if the memory usage for your AIR application is around 50 MB.
  7. Battery. Battery consumption is very important. If your application utilizes the hardware sensors, you may need to build an appropriate model to conserve the battery. For instance, if you are building a location-aware application, do not query the GPS sensor every few milliseconds. Also, implement Tombstoning to give those sensors a break!
  8. Graphics. With all those friendly IDEs and tools, anyone can build a mobile application. What differentiates your application from the ‘other’ applications is UI responsiveness and graphics. Spend more time in formulating the UI.
  9. Formats and Sync. If your mobile application connects to external services, understand the protocols and syncing methods. Will your application interact with a SOAP/REST-based service or an AMF endpoint? Also, understand the synchronous and asynchronous way of interacting with the remote services. How will you handle push messages? How will you sync the local data store with the remote store?
  10. Cloud. When you are building a mobile application that connects to the cloud, you need to understand the semantics of the cloud. The response returned from the cloud varies and it is your application’s responsibility to handle such disparities. For instance, in your application, if you are using UTF methods to read and write strings returned from a web service, your application may crash if the web service starts returning long strings. The cloud need not understand the semantics of the client but the client should understand the semantics of the cloud! Also, the cloud provides resilience, elasticity, and performance for your mobile applications. Always build applications that are controlled by the cloud.
  11. Finally, do not just build applications. Build solutions.

Building your first AIR-based mobile game in Burrito

The Adobe Flash Platform provides an elegant way to build, distribute, monetize, and play games on the  mobile platform. Once you learn the basics of ActionScript, Flex, and AIR, you can easily build simple to advanced games targeting various mobile devices.

Mobile games have gained immense popularity in the recent years primarily because of their ability to provide entertainment on the go. What does it mean for developers? There are numerous opportunities for game developers to produce and monetize their games on different online channels including the Android Market.

While you can use any language and tool to produce mobile games,  Flash Builder allows you to develop market-ready games with minimal effort. Moreover, Flash Builder provides a neat interface for building your game engine/levels and also allows you to debug your game on a connected device.

In this post, I’ll show you how you can build a simple Accelerometer-based game for the Android market using Adobe AIR and Flash Builder (Burrito). The objective of this game is to guide the earth ( image) towards the black hole (image) by using the accelerometer of the mobile device.

Now, if Accelerometer is available on the mobile device, you can initialize and handle the Accelerometer event as follows:

var acl:Accelerometer;
acl.addEventListener(AccelerometerEvent.UPDATE, handleACLUpdate);

private function handleACLUpdate(event:AccelerometerEvent):void{

    rollingX = (event.accelerationX * FACTOR) + (rollingX * (1-FACTOR));
    rollingY = (event.accelerationY * FACTOR) + (rollingY * (1-FACTOR));
    rollingZ = (event.accelerationZ * FACTOR) + (rollingZ * (1-FACTOR));

    earth.x = Math.round(earth.x - (rollingX*rollingSpeed));
    earth.y = Math.round(earth.y - (rollingY*rollingSpeed));

Accelerometer data obtained from the device has some degree of inaccuracy. You can use a moving average of recent data to smooth out the movement of the earth. For more information on the Accelerometer class, read the documentation.

You can move the earth by simply tilting the mobile device on any particular direction. You should also remember to align the earth back in to the stage when it moves out of screen bounds. To achieve this, we’ll use the Flex effects:

<s:Bounce id="beffect" />

<s:Move id="topbounce" target="{earth}" yBy="2" duration="100" />
<s:Move id="bottombounce" target="{earth}" yBy="-2" duration="100"   />
<s:Move id="leftbounce" target="{earth}" xBy="2" duration="100"
        easer="{beffect}" repeatCount="1"  />
<s:Move id="rightbounce" target="{earth}" xBy="-2" duration="100"
        easer="{beffect}" repeatCount="1"  />

The trick is to move the earth by a very few pixels in the opposite direction with a short animation so that the continuous Accelerometer effect on the earth image does not make the earth movement jerky. You can also vary the duration of the animation and the amount of pixels to move to achieve better smoothness.

At this point, you should read the Flex 4 documentation for more information on Flex effects.

You can use Flash Builder to create mobile views for adding the media assets. Learn more on Flex Mobile Views and Navigators. You can drag and drop images on the stage using the design view.

You need to embed the images for the effects to work.

After obtaining the Accelerometer inputs, you can choose to calculate the distance between the Black Hole image and the earth’s image. If the center points of both the images collide, raise an event to handle the collision. In our game, we increase the score. You can use the same concept to decrease the score when the earth hits any other rigid body apart from the black hole. The game play involves steering the earth to the black hole by carefully avoiding any stationary or moving objects.

I have built this simple game that will enable you to:

  • Create game levels. In this game, each View is a level.
  • Build ActionScript game engines. You can view and modify the sample code pertaining to health, score, and HUD management.
  • Understand and handle timers. Game timers control the duration of the game play. Excessive usage of timers will affect the game’s performance. Be warned!
  • Persist game data. You can serialize the game objects to the application storage directory. The sample game stores high scores for each level and supports auto saving.

Getting Started

  1. Before you begin, download and install Flash Builder Burrito.
  2. Download the Black Hole Flash Builder Project. Extract the archive to get the BlackHole.fxp file.
  3. Click File > Import Flash Builder Project and select BlackHole.fxp
  4. To run the sample game, select Run > Run. For the launch method, select ‘On device’ and click Run. Make sure that your Android device is connected to your computer through USB.

Also, in the sample game, you can drag and drop the earth in to the black hole if you get tired of using the Accelerometer. This test game is also available in the Android Market as ‘Black Hole’.

Happy Gaming!

AIR-Mobile Tip #1 Passing key-value pairs between views

This blog will start featuring tips and tricks for AIR-based application development on mobile devices. The tips are primarily for AIR and ActionScript developers who want to learn some tricks for quickly and effectively building applications for the mobile devices.

Tip: You can easily pass a key-value pair from one view to another view.

Here is a simple example:

MyView 1

<?xml version="1.0" encoding="utf-8"?>
    <s:View xmlns:fx=""
    xmlns:s="library://" title="Home">


          protected function button1_clickHandler(event:MouseEvent):void

      <s:Button x="178" y="196" label="Button" click="button1_clickHandler(event)"/>

In MyView1, we are passing a key-vale pair to MyView2 using the navigator.pushView method.

MyView 2

<?xml version="1.0" encoding="utf-8"?>
    <s:View xmlns:fx=""
    xmlns:s="library://" title="MyView" 
       viewActivate="view1_viewActivateHandler(event)" >


            private var userValue:String;

            protected function view1_viewActivateHandler(event:FlexEvent):void
                userValue = data.userKey;

In MyView2, we are receiving the key-value pair when the view gets activated.

Why would you need to pass key-value pairs between views? You can use this technique:

  • when you want to pass form values from one view to another.
  • when you want to pass user preferences.
  • when you want to route the view based on a key.
  • when you want to change the behavior of the view based on some keys. For instance, in a game, a view can read from the application storage directory and load the saved game or just start with a new game based on the values passed.

Apart from a key-value pair, you can also pass any untyped object from one view to another.