You are on page 1of 6

12/5/11 Androgames Android Accelerometer Sensor tutorial

1/6 blog.androgames.net/85/android-accelerometer-tutorial/
Andogame blog
Android Deelopment & Game
Home
Android Accelerometer Sensor tutorial
Posted by Tonio | Filed under Tutorial
Android supports a wide variety of sensors that can be used by applications to capture
informations about the phones environment.
In this tutorial, well see how to use the accelerometer sensor in an application in order to capture
acceleration change events. Well use these events to build a custom liene that will trigger
others events such as shake events :
package net.androgames.bolg.sample.accelerometer;

pblic inerface AccelerometerListener {

pblic oid onAccelerationChanged(floa x, floa y, floa z);

pblic oid onShake(floa force);

An instance of the SensorManager is required in order to retrieve informations about the


supported sensors. No permission is required to access the sensor service. It is then possible to
retrieve the list of available sensors of a certain type. For an accelerometer sensor, the type to
use is given by the Seno.TYPE_ACCELEROMETER constant. If at least one Sensor exists, it is
possible to register a SensorEventListener for a Sensor of the list. It is possible to specify the
delivering rate for sensor events. Specified rate must be one of :
1. SensorManager.SENSOR_DELAY_FASTEST : as fast as possible
2. SensorManager.SENSOR_DELAY_GAME : rate suitable for game
3. SensorManager.SENSOR_DELAY_NORMAL : normal rate
4. SensorManager.SENSOR_DELAY_UI : rate suitable for UI Thread
In order to allow a correct shake detection, it is preferable to use at least
SenoManage.SENSOR_DELAY_GAME.
The custom accelerometer manager is as follow :
Categories
Application
Tutorial
Archives
December 2010
September 2010
Jul 2010
Ma 2010
March 2010
Januar 2010
November 2009
October 2009
September 2009
M applications
Search...
12/5/11 Androgames Android Accelerometer Sensor tutorial
2/6 blog.androgames.net/85/android-accelerometer-tutorial/
package net.androgames.bolg.sample.accelerometer;

import java.util.List;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

/**
* Android Accelerometer Sensor Manager Archetpe
* @author antoine viane
* under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html
*/
public class AccelerometerManager {

/** Accurac configuration */
private static float threshold = 0.2f;
private static int interval = 1000;

private static Sensor sensor;
private static SensorManager sensorManager;
// ou could use an OrientationListener arra instead
// if ou plans to use more than one listener
private static AccelerometerListener listener;

/** indicates whether or not Accelerometer Sensor is supported */
private static Boolean supported;
/** indicates whether or not Accelerometer Sensor is running */
private static boolean running = false;

/**
* Returns true if the manager is listening to orientation changes
*/
public static boolean isListening() {
return running;


/**
* Unregisters listeners
*/
public static void stopListening() {
running = false;
tr {
if (sensorManager != null && sensorEventListener != null) {
sensorManager.unregisterListener(sensorEventListener);

catch (Exception e) {


/**
* Returns true if at least one Accelerometer sensor is available
*/
public static boolean isSupported() {
if (supported == null) {
if (Accelerometer.getContext() != null) {
sensorManager = (SensorManager) Accelerometer.getContext().
getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(
Sensor.TYPE_ACCELEROMETER);
supported = new Boolean(sensors.size() > 0);
else {
supported = Boolean.FALSE;


return supported;


/**
* Configure the listener for shaking
* @param threshold
* minimum acceleration variation for considering shaking
* @param interval
Thin-Film Pee Seno
Measure Tactile Pressure and Force.
Request a Free Custom Quote!
.Tekscan.com/Pressure-Sensors
Diff. Pee Seno
high accurac, calibrated, small,
cost-effective, long-term stabilit
.sensirion.com/diffpressure
Seno fo Robo
Tr the Amaing, Eas to Use
MaSonar Ultrasonic Range Sensor
.Maboti.com
12/5/11 Androgames Android Accelerometer Sensor tutorial
3/6 blog.androgames.net/85/android-accelerometer-tutorial/
* @paam ineal
* minimm ineal beeen o hake een
*/
pblic aic oid configure(in threshold, in interval) {
AccelerometerManager.threshold = threshold;
AccelerometerManager.interval = interval;


/**
* Regie a liene and a liening
* @paam acceleomeeLiene
* callback fo acceleomee een
*/
pblic aic oid startListening(
AccelerometerListener accelerometerListener) {
sensorManager = (SensorManager) Accelerometer.getContext().
getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(
Sensor.TYPE_ACCELEROMETER);
if (sensors.size() > 0) {
sensor = sensors.get(0);
running = sensorManager.registerListener(
sensorEventListener, sensor,
SensorManager.SENSOR_DELAY_GAME);
listener = accelerometerListener;



/**
* Confige hehold and ineal
* And egie a liene and a liening
* @paam acceleomeeLiene
* callback fo acceleomee een
* @paam hehold
* minimm acceleaion aiaion fo conideing haking
* @paam ineal
* minimm ineal beeen o hake een
*/
pblic aic oid startListening(
AccelerometerListener accelerometerListener,
in threshold, in interval) {
configure(threshold, interval);
startListening(accelerometerListener);


/**
* The liene ha lien o een fom he acceleomee liene
*/
piae aic SensorEventListener sensorEventListener =
ne SensorEventListener() {

piae long now = 0;
piae long timeDiff = 0;
piae long lastUpdate = 0;
piae long lastShake = 0;

piae floa x = 0;
piae floa y = 0;
piae floa z = 0;
piae floa lastX = 0;
piae floa lastY = 0;
piae floa lastZ = 0;
piae floa force = 0;

pblic oid onAccuracyChanged(Sensor sensor, in accuracy) {

pblic oid onSensorChanged(SensorEvent event) {
// e he een imeamp a efeence
// o he manage peciion on' depend
// on he AcceleomeeLiene implemenaion
// poceing ime
now = event.timestamp;

x = event.values[0];
y = event.values[1];
12/5/11 Androgames Android Accelerometer Sensor tutorial
4/6 blog.androgames.net/85/android-accelerometer-tutorial/
y = event.values[1];
z = event.values[2];

// if no ineeing in hake een
// j emoe he hole if hen ele bloc
if (lastUpdate == 0) {
lastUpdate = now;
lastShake = now;
lastX = x;
lastY = y;
lastZ = z;
else {
timeDiff = now - lastUpdate;
if (timeDiff > 0) {
force = Math.abs(x + y + z - lastX - lastY - lastZ)
/ timeDiff;
if (force > threshold) {
if (now - lastShake >= interval) {
// igge hake een
listener.onShake(force);

lastShake = now;

lastX = x;
lastY = y;
lastZ = z;
lastUpdate = now;


// igge change een
listener.onAccelerationChanged(x, y, z);


;

In the case of a SensorEvent triggered by a Sensor of type Sensor.TYPE_ACCELEROMETER, the


events values represents the acceleration of the phone given by a vector in a cartesian
coordinate system. Landing on a table, the values returned by the SensorEvent for the phone
should be :
1. 0 m/s
2
along x axis
2. 0 m/s
2
along y axis
3. 9,80665 m/s
2
along z axis
From an event to another, the coordinates of the acceleration vector are stored to detect suddent
acceleration changes and to trigger a shake event when the threshold is reached. Others events
could be implemented such as the detection of up and down gestures, circular gestures and lot
more
The custom AcceleromeerManager can be use in any Activity or Service :
package net.androgames.bolg.sample.accelerometer;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

/**
* Android accelerometer sensor tutorial
* @author antoine viane
* under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html
*/
public class Accelerometer etends Activity
implements AccelerometerListener {

private static Context CONTEXT;
12/5/11 Androgames Android Accelerometer Sensor tutorial
5/6 blog.androgames.net/85/android-accelerometer-tutorial/
piae aic Context CONTEXT;

/** Called when the activit is first created. */
@Override
pblic oid onCreate(Bundle savedInstanceState) {
pe.onCreate(savedInstanceState);
setContentView(R.layout.main);
CONTEXT = hi;


poeced oid onResume() {
pe.onResume();
if (AccelerometerManager.isSupported()) {
AccelerometerManager.startListening(hi);



poeced oid onDestroy() {
pe.onDestroy();
if (AccelerometerManager.isListening()) {
AccelerometerManager.stopListening();




pblic aic Context getContext() {
en CONTEXT;


/**
* onShake callback
*/
pblic oid onShake(floa force) {
Toast.makeText(hi, "Phone shaked : " + force, 1000).show();


/**
* onAccelerationChanged callback
*/
pblic oid onAccelerationChanged(floa x, floa y, floa z) {
((TextView) findViewById(R.id.x)).setText(String.valueOf(x));
((TextView) findViewById(R.id.y)).setText(String.valueOf(y));
((TextView) findViewById(R.id.z)).setText(String.valueOf(z));

As usual, it is preferable to register listeners in the onResume() method of the Activity and
removed in the onFinish() method of the Activity.
You can browse the full source code of the Eclipse project here : SampleAccelerometerSensor
Enjoy !
Tags : accelerometer, gesture, sensor, shake
Permalink March 6th, 2010
Leave a Repl
Name
Mail (ill not be published)
Website
12/5/11 Androgames Android Accelerometer Sensor tutorial
6/6 blog.androgames.net/85/android-accelerometer-tutorial/
Webie
Commen
Sbmi Commen
Recent Posts
Aomaic Andoid obfcaed bild
Andoid iled backgond
Andoid TakKille applicaion
Andoid com Dialog
Andoid Bbble Leel applicaion
Links
Andoid make - Andoid make official ie
Deelope eoce - Andoid deelope' gide
Tonio' Blog - Andoid oial in Fench
About
Copyright 2011 Andogame blog

You might also like