Q: Android: I want to shake it

D: I need to add a shake feature that will refresh my Android application.
All I find of documentation involves implementing the SensorListener, but Eclipse tells me it's deprecated and suggest SensorEventListener.
Anybody that has a nice guide to how I go about creating this shake controller?

Test Case #5


File ID: #2318356-1-cc


   @Override
public void onSensorChanged(SensorEvent event) {
// ignore motion events if a shake event occured less than 1 second ago
if ((System.currentTimeMillis() - lastShakeEvent) < 1000L) {
return;
}
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
accelLast = accelCurrent;
accelCurrent = (float) Math.sqrt((double) (x * x + y * y + z * z));
float delta = accelCurrent - accelLast;
accel = accel * 0.9f + delta;
if (accel >= 2.0f) {
fireShakeEvent();
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().getDecorView().getRootView()
.setBackgroundColor(COLORS[0]);
setContentView(R.layout.activity_main);
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
accel = 0.00f;
accelCurrent = SensorManager.GRAVITY_EARTH;
accelLast = SensorManager.GRAVITY_EARTH;
}


  1. Is this line of code `mAccel = mAccel * 0.9f + delta; // perform low-cut filter` supposed to be `mAccel = mAccel * 0.9f + delta * 0.1f; // perform low-cut filter`?
  2. The compiler suggests to use: `android.util.FloatMath.sqrt(x*x + y*y + z*z);` instead to avoid a conversion
  3. To test this, use the following: if (mAccel > 12) { Toast toast = Toast.makeText(getApplicationContext(), "Device has shaken."", Toast.LENGTH_LONG); toast.show(); }

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: