How to:‎ > ‎

use the accelerometer

Android Accelerometer How-To

Typical Android devices have all kinds of different Sensors. One of the is the accelerometer.
With this feature you can sense
orientation, vibration and shock.

To get a list of all available sensors:

 
sensorManager = (SensorManager) parent.getSystemService(Context.SENSOR_SERVICE);
        List<Sensor> sen=sensorManager.getSensorList(Sensor.TYPE_ALL);
      
        for(Sensor s:sen){
           Log.i("Sensors","sensor :"+s.getName()+ " - Type: "+s.getType()+ " \n");
        }


Here is an example how to show the Axis Values in an Activity.
text_a and text_b are TextViews.

event has an array named values with 3 entries:

value[0] = X
value[1] = Y
value[2] = Z

You can give the Eventlistner a rate often you want the data.
The four options are:
SENSOR_DELAY_NORMAL, SENSOR_DELAY_UI, SENSOR_DELAY_GAME, or SENSOR_DELAY_FASTEST.



   
   
        sensorManager = (SensorManager).getSystemService(Context.SENSOR_SERVICE);
    
        sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
       
      
          sensorManager.registerListener(new SensorEventListener() {
           
            @Override
            public void onSensorChanged(SensorEvent event) {
          
           
              
                text_A.setText(  " x-axis "+ event.values[0] + "\n" +
                                    " y-axis "+event.values[1] + "\n" +
                                    " z-axis " + event.values[2] +"");
         }
           
           
            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
              
            text_b.setText(sensor.getName() + " - "+ accuracy );
               
               
            }
        }, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_NORMAL );
             
           
           
       
    }

Watch out if you using Tutorials out of the internet. Apparently they just changed the API recently. So they all
use depricated methods and objects. I had to create this just out of the API Documentation only, so i hope it helps.
 
created by Lukas Jarosch

Comments