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 following code. First, you will notice that there
is a private variable named accelerometer declared of
type flash.sensors.Accelerometer. Within the applicationComplete event
of the application, an event handler function is called; it 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 TextArea within the
handleUpdate function. The results are shown in Figure 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;
private var accelerometer:Accelerometer;
protected function application1_applicationCompleteHandler
(event:FlexEvent):void {
if(Accelerometer.isSupported==true){
accelerometer = new Accelerometer();
accelerometer.addEventListener
(AccelerometerEvent.UPDATE,handleUpdate);
} else {
status.text = "Accelerometer not supported";
}
}
private function handleUpdate(event:AccelerometerEvent):void {
info.text = "Updated: " + new Date().toTimeString() + "\n\n"
+ "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>