How to use Accelerometer in Android?

By | May 30, 2012

This is a simple post showing how to use accelerometer in android.

This java code prints the values of x,y and z axis in the console.

package com.coderzheaven.pack;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;

public class AccelerometerTest extends Activity  implements SensorEventListener{
	 private SensorManager sensorManager;
	 double ax,ay,az;   // these are the acceleration in x,y and z axis

    public void onCreate(Bundle savedInstanceState) {
         sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
         sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    public void onAccuracyChanged(Sensor arg0, int arg1) {

    public void onSensorChanged(SensorEvent event) {
         if (event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
                     System.out.println("X = " + ax + ", Y = " + ay +", Z = " + az);

Leave your comments on this post.
Find Coderzheaven on facebook, twitter , google Plus and MySpace for more updates.

Leave a Reply

Your email address will not be published. Required fields are marked *