Accelerometer Usage

The purpose of this blog post is to quickly and easily show someone how to utilize the accelerometer sensor on their android phone. Be sure to read the comments in the code, as they explain certain parts that are important.

First we need to set up some variables in the main area of our class. Assuming that it is an activity, we need to have it so that it Implements SensorEventListener

publicfloatlx, ly, lz;


public SensorManager mSensorManager;

public Sensor mAccelerometer;

publicfinalfloatNOISE = (float) 3;

The lx, ly, and lz will store the previous values of the sensor’s values. The NOISE Float is used to filter out small motions that the phone makes so that only significant ones register. I have found that anything that registers more than a 15 on the sensor is a pretty solid shake. I feel like somewhere between 3 and 5 is a good spot to avoid accidental triggering of events.

Next, in the onCreate function we will need the following:

Initialized = false;

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);

The next step is to implement the function onSensorChanged, which activates every time the accelerometer values change.


publicvoid onSensorChanged(SensorEvent event) {

// Have a textview to view the sensor changes

TextView tx = (TextView) findViewById(;

//Gets x,y, and z values for the accelerometer.

float x = event.values[0];

float y = event.values[1];

float z = event.values[2];

if (!Initialized) {

lx = x;

ly = y;

lz = z;

Initialized = true;


else {

// get the absolute value of movement on x-axis

float deltaX = Math.abs(lx – x);

if(deltaX > NOISE){

//When X movement reaches a certain point… it does this:



//put current sensor values into previous sensor values

lx = x;

ly = y;

lz = z;



And there you have it. A quick simple framework that can get you using the android accelerometer in no time.