Search code examples
androidaccelerometer

Displaying Accelerometer Values in Android


I am looking for some source code or example code detailing how to display the values of the accelerometer in Android. Preferably, the values would show acceleration in the x direction, y direction, and z direction.

I am an Android noob so any help is much appreciated.


Solution

  • Have you checked out the Accelerometer example in the android samples? You could always try something like this (which I got from here):

     public class SensorActivity extends Activity implements SensorEventListener {
         private final SensorManager mSensorManager;
         private final Sensor mAccelerometer;
    
         public SensorActivity() {
             mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
             mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
         }
    
         protected void onResume() {
             super.onResume();
             mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
         }
    
         protected void onPause() {
             super.onPause();
             mSensorManager.unregisterListener(this);
         }
    
         public void onAccuracyChanged(Sensor sensor, int accuracy) {
         }
    
         public void onSensorChanged(SensorEvent event) {
           //Right in here is where you put code to read the current sensor values and 
           //update any views you might have that are displaying the sensor information
           //You'd get accelerometer values like this:
           if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
                return;
            float mSensorX, mSensorY;
            switch (mDisplay.getRotation()) {
                case Surface.ROTATION_0:
                    mSensorX = event.values[0];
                    mSensorY = event.values[1];
                    break;
                case Surface.ROTATION_90:
                    mSensorX = -event.values[1];
                    mSensorY = event.values[0];
                    break;
                case Surface.ROTATION_180:
                    mSensorX = -event.values[0];
                    mSensorY = -event.values[1];
                    break;
                case Surface.ROTATION_270:
                    mSensorX = event.values[1];
                    mSensorY = -event.values[0];
             }
         }
     }