How do I use the Android Accelerometer?

user642866 picture user642866 · Mar 3, 2011 · Viewed 87.2k times · Source

I'm trying to build an app for reading the values from the accelerometer on my phone, which supports Android 2.1 only.

How do I read from the accelerometer using 2.1-compatible code?

Answer

ArcDare picture ArcDare · Nov 12, 2011

Start with this:

public class yourActivity extends Activity implements SensorEventListener{
 private SensorManager sensorManager;
 double ax,ay,az;   // these are the acceleration in x,y and z axis
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
   }
   @Override
   public void onAccuracyChanged(Sensor arg0, int arg1) {
   }

   @Override
   public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
            ax=event.values[0];
                    ay=event.values[1];
                    az=event.values[2];
            }
   }
}