Tuesday 19 April 2011

Android - Accelerometer Tutorial

Android devices come with various sensors such as proximity sensors, pressure sensors, accelerometer, gyroscope, light sensor, magnetometer, thermometer, etc.,

In this tutorial we will be using accelerometer. To summarize the tasks:
1. Obtain a reference to the SensorManager.
2. Register a sensor listener for the accelerometer.
3. Make updates from the SensorListener callbacks.

MainActivity.java
 package com.mobsandgeeks.ad;  
   
 import android.app.Activity;  
 import android.content.Context;  
 import android.hardware.SensorListener;  
 import android.hardware.SensorManager;  
 import android.os.Bundle;  
 import android.widget.TextView;  
   
 @SuppressWarnings("deprecation")  
 public class MainActivity extends Activity implements SensorListener {  
      //References to the TextViews defined in main.xml  
      private TextView xValue;  
      private TextView yValue;  
      private TextView zValue;  
      
      //Reference to the SensorManager  
      private SensorManager sensorManager;  
        
      @Override  
      public void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.main);  
       
           //Obtain references to the Views from the content view  
           xValue = (TextView) findViewById(R.id.x_value);  
           yValue = (TextView) findViewById(R.id.y_value);  
           zValue = (TextView) findViewById(R.id.z_value);  
       
           sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); //Reference to the SensorManager  
           sensorManager.registerListener(this, SensorManager.SENSOR_ACCELEROMETER); //Registering the sensor listener for the accelerometer  
      }  
   
      @Override  
      public void onAccuracyChanged(int sensor, int accuracy) {  
      }  
   
      @Override  
      public void onSensorChanged(int sensor, float[] values) {  
           float x = values[SensorManager.RAW_DATA_X]; //Raw X value for the accelerometer  
           float y = values[SensorManager.RAW_DATA_Y];     //Raw X value for the accelerometer  
           float z = values[SensorManager.RAW_DATA_Z];     //Raw X value for the accelerometer  
             
           //Update TextViews  
           xValue.setText("X: " + x);  
           yValue.setText("Y: " + y);  
           zValue.setText("Z: " + z);  
      }  
 }  

Source Code
You can download the source code from here.

Screenshot

No comments:

Post a Comment