Accelerometer

0
150

The accelerometer is a device that measures the speed or g-forces created when a device accelerates across multiple planes. The faster the device is moved through space, the higher the readings will be across the x, y, and z axes.

Let’s review the code below. First, you will notice that there is a private variable named accelerometer declared, of type flash.sensors.Accelerometer. Within applicationCom plete of the application, an event handler function is called, which first checks to see if the device has an accelerometer by reading the static property of the Accelerometer class. If this property returns as true, a new instance of Accelerometer is created and an event listener of type AccelerometerEvent.UPDATE is added to handle updates. Upon update, the accelerometer information is read from the event and written to a Text Area within the handleUpdate function. The results can be seen within Figure 4-1:

<?xml version=”1.0″ encoding=”utf-8″?>
<s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009″
xmlns:s=”library://ns.adobe.com/flex/spark”
applicationComplete=”application1_applicationCompleteHandler(event)”>
<fx:Script>
<![CDATA[
import flash.sensors.Accelerometer;
import mx.events.FlexEvent;
privatevar accelerometer:Accelerometer;
protectedfunction application1_applicationCompleteHandler
(event:FlexEvent):void {
if(Accelerometer.isSupported==true){
accelerometer = new Accelerometer();
accelerometer.addEventListener(AccelerometerEvent.
UPDATE,handleUpdate);
} else {
status.text = “Accelerometer not supported”;
}
}
privatefunction handleUpdate(event:AccelerometerEvent):void {
info.text = “Updated: ” + new Date().toTimeString() + “nn”
+ “acceleration X: “+ event.accelerationX + “n”
+ “acceleration Y: ” + event.accelerationY + “n”
+ “acceleration Z: ” + event.accelerationZ;
}
]]>
</fx:Script>

<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>
<s:Label id=”status” text=”Shake your phone a bit” top=”10″ width=”100%”
textAlign=”center”/>
<s:TextArea id=”info” width=”100%” height=”200″ top=”40″ editable=”false”/>
</s:Application>

 

Accelerometer information