Detecting shakes on a Flash 10.1 enabled Android Device using ActionScript

Posted in Software Development on May 26th, 2010 by Russ Tarleton

How to detect a Shake

Pre-requisite: Install AIR SDK into CS5 (Must be a part of the Public Beta)

  1. Login to prerelease.adobe.com
  2. Browse to Home > AIR for Android Developer Prerelease > Documentation > Documentation [05/20/10]
  3. Click on “AIR Android ReleaseNotes 0520.html”
  4. Click on “How to Update Flash CS5 to Use the AIR SDK
  5. Follow the 7-step instructions to install the Flash extension file


Reference API

Accelerometer: http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/sensors/Accelerometer.html
AccelerometerEvent: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/AccelerometerEvent.html


Code

// Import the correct classes – if Flash returns an error for either of these, then you have not correctly installed the AIR API yet.
import flash.events.AccelerometerEvent;
import flash.sensors.Accelerometer;

// Add this constant to your class – it determines how often the shake should do something (currently every half a second)
private static const _SHAKE_WAIT = 500;

// Add these two private variables to your class
private var _accl                 : Accelerometer;
private var _lastShake             : Number = 0;

// Put this where you initialize your class – it detects if accelerometer is supported on the device and adds the listener
if (Accelerometer.isSupported)
{
_accl = new Accelerometer();
_accl.addEventListener(AccelerometerEvent.UPDATE, onAccelerometer);
}

// Put this where you destroy your class – it detects if accelerometer is supported on the device and removes the listener
if (Accelerometer.isSupported)
{
_accl.removeEventListener(AccelerometerEvent.UPDATE, onAccelerometer);
}

// Add this method to your class – it is the callback for the accelerometer
private function onAccelerometer(e:AccelerometerEvent) : void
{
if (getTimer() – _lastShake > _SHAKE_WAIT && (e.accelerationX >= 2 || e.accelerationY >= 2 || e.accelerationZ >= 2))
{
doShake(); // Replace “doShake();” with a call to the method you wish to execute when the shake occurs.
_lastShake = getTimer(); // Reset the timer so that this code block doesn’t happen again until _SHAKE_WAIT milliseconds later.
}
}