Accelerometer Flash Builder 4.5 Mobile

 

This tutorial is a guide to how you access the accelerometer in Flash Builder 4.5 for mobile devices. We are going to create an app that simulates a lifelike ball rolling around on the mobile phone screen. You need to know how to create an ActionScript Mobile Project in Flash Builder 4.5 to start this tutorial. You find my tutorial on how to create an ActionScript Mobile Project in Flash Builder 4.5 here.

You find the complete ActionScript code for this Flash Builder project at the bottom of the page.

Create a new ActionScript Mobile Project, I recommend checking the checkbox for full screen and DISABLE_KEYGARD, WAKE_LOCK if you are targeting Google Android. The later will let us prevent the mobil screen from going into idle mode.

The first thing that we need to address in this tutorial is to check whether or not the users device supports the accelerometer. We do this by checking the static property isSupported on the Accelerometer class. We will only run the app if this property is true.

Accelerometer.isSupported

So we create an IF statement and place our code inside. The first thing to do after checking if the accelerometer is supported is to create an instance of the Accelerometer class.

_acc = new Accelerometer();

The accelerometer dispatches update events repeatedly. We need to add an event listener to capture this event and update the position and speed of the ball according to how the user tilts the mobile device.

_acc.addEventListener(AccelerometerEvent.UPDATE, onAccUpdate);

We can request how often we like the accelerometer to dispatch update events. We request this interval in milliseconds but this is only a hint to preserve battery power. The accentual interval may be greater or smaller than the requested. We do not need to request an interval for the accelerometer to work. But I will show you how it is done in ActionScript.

_acc.setRequestedUpdateInterval(50);

We also need to move the ball around. We add an event listener for the enterFrame event and will later add the code for moving the ball in this listener.

addEventListener(Event.ENTER_FRAME, onEnterFrame);

We also need a ball to move. We create an instance of the Shape class, which is a lightweight display object, and draw a red circle with radius 50 on it. We cache it as a bitmap to speed up the app on low end mobile devices. Finally we add the ball to the display list using the addChild method.

_ball = new Shape();
_ball.graphics.beginFill(0xff0000);
_ball.graphics.drawCircle(0, 0, 50);
_ball.cacheAsBitmap = true;
addChild(_ball);

One last thing that is good to add is to prevent the mobile screen from going to sleep. Most mobile phones and devices will turn of the screen if you do not tap on the screen for some short time. We will only tilt the device to move the ball and the screen will soon turn of. You can add the following code to disable the screen from going to sleep. You also need to check the checkbox for DISABLE_KEYGARD, WAKE_LOCK if you are targeting Google Android when you create the project or edit the *-app.xml if you already crated the ActionScript Mobile Project. More info about preventing mobile phone from going into idle mode can be found in my tutorial about that found here.

NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE;

That is all the code needed for initiating the app. Now lets create the event listener for the accelerometer update event. The event dispatched is of the type AccelerometerEvent and it has the parameters accelerationX, accelerationY that we are interested in. We update the current speed with accelerations in both directions using a factor to scale the values.

_speedX += e.accelerationX * _speedFac;
_speedY += e.accelerationY * _speedFac;

We then apply some friction to simulate a real ball. The friction value should be smaller than 1 to slow the ball down.

_speedX *= _friction;
_speedY *= _friction;

Last thing to do is to create the event listener for the enter frame event. The only thing we need to do here is update the current position according to our speed.

_ball.x -= _speedX;
_ball.y += _speedY;

You find the complete ActionScript code bellow.

package
{
   import flash.desktop.NativeApplication;
   import flash.desktop.SystemIdleMode;
   import flash.display.Shape;
   import flash.display.Sprite;
   import flash.events.AccelerometerEvent;
   import flash.events.Event;
   import flash.sensors.Accelerometer;
   
   public class AccTest extends Sprite
   {
      private var _acc:Accelerometer;
      private var _ball:Shape;
      private var _speedX:Number = 0;
      private var _speedY:Number = 0;
      private var _speedFac:Number = 10;
      private var _friction:Number = 0.9;
      
      public function AccTest()
      {
         init();
      }
      
      protected function init():void
      {
         if (Accelerometer.isSupported)
         {
            _acc = new Accelerometer();
            _acc.addEventListener(AccelerometerEvent.UPDATE, onAccUpdate);
            _acc.setRequestedUpdateInterval(50);
            
            addEventListener(Event.ENTER_FRAME, onEnterFrame);
                        
            _ball = new Shape();
            _ball.graphics.beginFill(0xff0000);
            _ball.graphics.drawCircle(0, 0, 50);
            _ball.cacheAsBitmap = true;
            addChild(_ball);
            
            NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE;
         }
         else
         {
            // Handle case when the accelerometer is not supported here
         }
      }
      
      protected function onAccUpdate(e:AccelerometerEvent):void
      {
         _speedX += e.accelerationX * _speedFac;
         _speedY += e.accelerationY * _speedFac;
         
         _speedX *= _friction;
         _speedY *= _friction;
      }
      
      protected function onEnterFrame(e:Event):void
      {
         _ball.x -= _speedX;
         _ball.y += _speedY;
      }
   }
}

This is all there is to it. Compile the ActionScript Mobile Project in Flash Builder 4.5 and run it on your mobile device to test it. Remember that nothing will happen if you test the app on your computer since you do not have an accelerometer on it. You need to run the app on your mobile phone or device that has an accelerometer.

That concludes this tutorial. Learn more about ActionScript 3.0, Flash Builder 4.5 and the Flex framework in our other tutorials on this site. I hope you have enjoyed this ActionScript tutorial about using the Accelerometer in Flash Builder 4.5.