viernes, 7 de junio de 2013

Shake Listener for Android

Something is not implemented is a default shake listener for Android.
Here is my solution I steal from Stackoverflow

public class ShakerActivity extends Activity implements SensorEventListener{

 private SensorManager mSensorManager;
 private float mAccel; // acceleration apart from gravity
 private float mAccelCurrent; // current acceleration including gravity
 private float mAccelLast; // last acceleration including gravity
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
  
              /* do this in onCreate */
              mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    
              mAccel = 0.00f;
              mAccelCurrent = SensorManager.GRAVITY_EARTH;
              mAccelLast = SensorManager.GRAVITY_EARTH;
  
        }

 @Override
 protected void onResume() {
  super.onResume();
  
  mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
 }
 
 @Override
 protected void onPause() {
  super.onPause();
  
  mSensorManager.unregisterListener(this);
  
 }

 @Override
 public void onAccuracyChanged(Sensor sensor, int accuracy) {
  // TODO Auto-generated method stub
  
 }

 @Override
 public void onSensorChanged(SensorEvent event) {
  
  float x = event.values[0];
  float y = event.values[1];
  float z = event.values[2];
  mAccelLast = mAccelCurrent;
  mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
  float delta = mAccelCurrent - mAccelLast;
  mAccel = mAccel * 0.9f + delta; // perform low-cut filter
  
                //if mAccel is greater than 2 mobile is being shaked
  if(mAccel>2){
  
   //TODO: put the code you want to execute when mobile is shaked
  }
  
 }
}

No hay comentarios:

Publicar un comentario