0

Is there a simple way to detect a shake, if there are multiple shakes one after the other then set a counter and when the counter has reached a limit then it stops counting?

SpunkTrumpet
  • 133
  • 4
  • 10

2 Answers2

3

From the code point of view, you need to implement the SensorListener:

public class ShakeActivity extends Activity implements SensorListener

You will need to acquire a SensorManager:

sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);

And register this sensor with desired flags:

ensorMgr.registerListener(this,
SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_GAME);

In your onSensorChange() method, you determine whether it’s a shake or not:

public void onSensorChanged(int sensor, float[] values) {
  if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
    long curTime = System.currentTimeMillis();
    // only allow one update every 100ms.
    if ((curTime - lastUpdate) > 100) {
      long diffTime = (curTime - lastUpdate);
      lastUpdate = curTime;

      x = values[SensorManager.DATA_X];
      y = values[SensorManager.DATA_Y];
      z = values[SensorManager.DATA_Z];

      float speed = Math.abs(x+y+z – last_x – last_y – last_z) / diffTime * 10000;

      if (speed > SHAKE_THRESHOLD) {
        Log.d("sensor", "shake detected w/ speed: " + speed);
        Toast.makeText(this, "shake detected w/ speed: " + speed, Toast.LENGTH_SHORT).show();
      }
      last_x = x;
      last_y = y;
      last_z = z;
    }
  }
}

The shake threshold is defined as:

private static final int SHAKE_THRESHOLD = 800;

There are some other methods too, to detect shake motion. look at this link.(If that link does not work or link is dead, look at this web archive.).

Thanks.

Harshal Doshi Jain
  • 2,379
  • 1
  • 16
  • 15
-1

You can Implement the SensorManager class.

Check answers and links Here.

Community
  • 1
  • 1
gilonm
  • 1,719
  • 1
  • 10
  • 22