Retrieving accelerometer data

The accelerometer is designed to track the direction and speed of the movement along an x, y, and z axis when a BlackBerry® device user moves the BlackBerry device. The x axis is parallel to the width of the BlackBerry device. The y axis is parallel to the length of the BlackBerry device. The z axis is parallel to the depth (front to back) of the BlackBerry device. For more information about the x, y, and z axes of the accelerometer, see the net.rim.device.api.system.AccelerometerSensor class in the API reference for the BlackBerry® Java® Development Environment.

You can enable a BlackBerry device application to react to the acceleration of the BlackBerry device that includes an accelerometer. For example, a BlackBerry device user could move the BlackBerry device to control the direction and speed of an object that moves through a maze in a game application.

You can use the Accelerometer APIs, in the net.rim.device.api.system package, to react to the acceleration of the BlackBerry device. You must first determine whether the BlackBerry device supports an accelerometer by invoking net.rim.device.api.system.AccelerometerSensor.isSupported(). If the method returns the value true, the BlackBerry device supports an accelerometer.

You can use the AccelerometerData class to identify the direction the user moves the BlackBerry device. Invoking AccelerometerData.getOrientation() returns one of the AccelerometerSensor class constants that correspond to the direction of the BlackBerry device. For example, if AccelerometerData.getOrientation() returns a value equal to AccelerometerSensor.ORIENTATION_LEFT_UP, the left side of the BlackBerry device is in an upward direction.

You can use the AccelerometerSensor class to retrieve acceleration data from the BlackBerry device. Invoking AccelerometerSensor.openRawDataChannel() returns an object of the net.rim.device.api.system.AccelerometerSensor.Channel class. The AccelerometerSensor.Channel class allows you to open a connection to the accelerometer. You can retrieve data from the accelerometer by invoking AccelerometerSensor.Channel.getLastAccelerationData().

Maintaining a connection to the accelerometer uses power from the BlackBerry device battery. When the BlackBerry device application no longer needs to retrieve data from the accelerometer, you should invoke AccelerometerSensor.Channel.close() to close the connection.

Code sample: Retrieving data from the accelerometer

short[] xyz = new short[3];
while( running ) {
    channel.getLastAccelerationData(xyz);
}
channel.close();

Was this information helpful? Send us your comments.