I am trying to include shake functionality in my app. For that i require to intent an activity upon phone shake irrespective of where the user is in the application. Now i placed my sensor code in the application class but in order to intent it requires context. Am i on a right way or is there any other way to achieve this functionality ? Here's my code
public class MyApplication extends Application {
/* variables for shake detection */
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
public void onCreate(){
/* sensor shake detection */
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;
}
private final SensorEventListener mSensorListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent se) {
float x = se.values[0];
float y = se.values[1];
float z = se.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 > 3.0f)
{
// Toast.makeText(getBaseContext(), "Phone shaked", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),LiveSearchActivity.class);
startActivity(intent);
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}