Search code examples
androidnullaccelerometer

Android Accessing Accelerometer: Returns always 0 as Value


i would like to use the accelerometer in an Android Handset for my Application. The data from the sensor will be saved together with a GPS Point, so the Value is only needed when the GPS Point is updated.

If i use the attached Code the values is always zero. API Level 8 Permissions: Internet, Fine Location Testing Device: Galaxy S(i9000), Nexus One

Any Suggestions? I am stuck at this point.

Best regards from Germany, Pascal

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

public class AccelerometerService extends Activity{
    AccelerometerData accelerometerData;
    private SensorManager mSensorManager;
    private float x,y,z;
    private class AccelerometerData implements SensorEventListener{ 

        public void onSensorChanged(SensorEvent event) {
            x = event.values[0];
            y = event.values[1];
            z = event.values[2];
        }
        public void onAccuracyChanged(Sensor sensor, int accuracy) {}
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mSensorManager.registerListener(accelerometerData,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_FASTEST);
    }
    @Override
    protected void onResume() {
        super.onResume();  
    }
    @Override
    protected void onStop() {
        mSensorManager.unregisterListener(accelerometerData);
        super.onStop();
    }
    public String getSensorString()
    {
        return ("X: " + x+"m/s, Y: "+ y +"m/s, Z: "+ z +"m/s" );
    }
}

Solution

  • Do you assign a value to accelerometerData at any point? I would have expected it to be assigned in the onCreate method.

    You may also need to account for the screen orientation and filter out any non-accelerometer events that come in (I'm not sure if the filtering is absolutely necessary, but it's in the Accelerometer Play SDK sample.