Tuesday, February 28, 2012

Example for SensorListener in Android?


public class TestActivity extends Activity implements SensorEventListener {
   private SensorManager mgr;
   private Sensor sensorAccelerometer;
   private long lastUpdate;
   private float lastX = 0.5f;
   private float lastY = 0.5f;
   private float lastZ = 0.9f;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setActionBarContentView(R.layout.testactivity);
   
      mgr = (SensorManager)getSystemService(SENSOR_SERVICE);
      sensorAccelerometer = mgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
   }
  
   @Override
   protected void onResume() {
      super.onResume();
      mgr.registerListener(this, sensorAccelerometer, SensorManager.SENSOR_DELAY_UI);
   }
  
   @Override
   protected void onPause() {
      super.onPause();
      mgr.unregisterListener(this);
   }
 
   @Override
   public void onAccuracyChanged(Sensor sensor, int accuracy) {
      // TODO Auto-generated method stub
   }
 
   @Override
   public void onSensorChanged(SensorEvent event) {
      if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
         long currTime = System.currentTimeMillis();
    
         if((currTime - lastUpdate) > 1000){ //just scan every second
            lastUpdate = currTime;
      
            float xAxis = event.values[SensorManager.DATA_X];
            float yAxis = event.values[SensorManager.DATA_Y];
            float zAxis = event.values[SensorManager.DATA_Z];
     
            String comment = inMovement(xAxis, yAxis, zAxis) ? "not moving" : "in movement";
     
            publishValues(xAxis, yAxis, zAxis, comment);
     
            lastX = xAxis;
            lastY = yAxis;
            lastZ = zAxis;
         
      }
   }
 
   private boolean inMovement(float xAxis, float yAxis, float zAxis) {
      final float tolerance = 0.5f;
   
      if(Math.abs(xAxis - lastX) <= tolerance && Math.abs(yAxis - lastY) <= tolerance && Math.abs(zAxis - lastZ)<=tolerance){
         return true;
      }else
         return false;
      }
 
      private void publishValues(float x, float y, float z, String comment) {
         TextView mainText =(TextView)findViewById(R.id.textView);
   
         mainText.setText("X: " + x + " - Y: " + y + " - Z: " + z + "\nComment: " + comment);
      }
}




No comments:

Post a Comment