Chapter 6. Detecting Motion with Accelerometer


  • Detecting motions in your app

  • Working with Accelerometer and AccelerometerEvent classes

  • Detecting when the user shakes the device

Android and iOS devices have built-in motion detectors that enable programmers to capture the motion that occurs on a three-dimensional axis. This capability enables you to detect all sorts of user motions — tilting the phone, shaking back and forth, and rotating it in a circular fashion.

This chapter introduces you to the Accelerometer and AccelerometerEvent classes and shows you how to detect motion in your apps. It walks you through the creation of three apps that demonstrate different aspects of motion detection:

  • AccelerateInfo, which lists raw data from the motion sensor

  • SphereAcceleration, which uses the Accelerometer to guide a sphere around the viewport

  • Shakey, which captures a shake event

However, before beginning, it's important to introduce you to the two classes you'll work with to detect motion.


There are two main classes that you work with to use a mobile device's motion sensor: Accelerometer and AccelerometerEvent. Android and iOS enable you to return movement data of the device along the x, y, and z axes to your app. The data you receive is in Gs. One G is the gravitational constant equal to 9.8m/sec2.

The Accelerometer class is used for basic setup purposes: checking for motion sensor support on the device, assigning a listener ...

Get Professional Flash® Mobile Development: Creating Android™ and iPhone® Applications now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.