Detecting and responding to an orientation change

How to

Detect and respond to an orientation change.


Set up your accelerometer and add an event listener

// Enable accelerometer tracking
var accel:Accelerometer = new Accelerometer();

// Define update to listen for and name of function to dispatch when it occurs
accel.addEventListener(AccelerometerEvent.UPDATE, onUpdate);

Create the function that is called to react to your event

public function onUpdate(event:AccelerometerEvent):void
     var strStatus:String;
     if(event.accelerationX > 0.5)
         strStatus = "Device orientation: Left side up";
     else if(event.accelerationX < -0.5)
         strStatus = "Device orientation: Right side up";
     else if(event.accelerationY > 0.5)
         strStatus = "Device orientation: Standing";
     else if(event.accelerationY < -0.5)
         strStatus = "Device orientation: Standing upside down";
     else if(event.accelerationZ > 0.5)
         strStatus = "Device orientation: Face up";
     else if(event.accelerationZ < -0.5)
         strStatus = "Device orientation: Face down";

    // Output results
    trace (strStatus);

Build requirements

You must include the following classes in the class:

import flash.sensors.Accelerometer;


To react to an orientation change, declare an Accelerometer variable, and add an event listener to handle an AccelerometerEvent.UPDATE event. To add functionality, you can then evaluate the event.accelerationX, event.accelerationY, and event.accelerationZ values in the function called by that listener to detect the direction of gravity and react accordingly.

You should lock your application's orientation if your application is designed to track orientations where the device is positioned sideways or with the screen facing down.