Search code examples
javaandroidlocationaccelerometer

Access how much a device moved using accelerometer in android studio?


(I am a beginner in android, please go easy on me)

I am making an app that requires precision locating and calculating the difference between two very close locations. I highly doubt that this precision is achievable with GPS, and for now I am working with higher end phones which have good accelerometers. Basically, how do I access how much a device moved, with extreme precision?


Solution

  • You can start with this to just get the accelerometer. I have not done anything with this feature before.

    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];
                }
       }
    }
    

    Here is a link for a guide that seems pretty thorough and might help you down your path. Using The Accelerometer