摇动检测计数器

时间:2014-02-11 16:22:42

标签: java android eclipse shake

是否有一种简单的方法可以检测到震动,如果一个接一个地振动多次,然后设置一个计数器,当计数器达到极限时,它会停止计数?

2 个答案:

答案 0 :(得分:3)

从代码的角度来看,您需要实现SensorListener:

public class ShakeActivity extends Activity implements SensorListener

您需要获取SensorManager:

sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);

并使用所需的标志注册此传感器:

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

在你的onSensorChange()方法中,你确定它是否是一个震动:

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;
    }
  }
}

震动阈值定义为:

private static final int SHAKE_THRESHOLD = 800;

还有一些其他方法可以检测摇动。看看这个link.(如果该链接不起作用或链接已死,look at this web archive。)。

感谢。

答案 1 :(得分:-1)

您可以实施SensorManager课程。

检查答案和链接Here