1

当我摇动设备时,我使用 sensorevenetlistner 触发了一个意图,问题只是一点点摇动,意图正在触发,但我希望它仅在我摇动设备 3 次或一定次数的摇动时触发

private void getAccelerometer(SensorEvent event) {
    float[] values = event.values;
    // Movement
    float x = values[0];
    float y = values[1];
    float z = values[2];

    float accelationSquareRoot = (x * x + y * y + z * z)
        / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
    long actualTime = System.currentTimeMillis();
    if (accelationSquareRoot >= 2) //
    {
      if (actualTime - lastUpdate < 200) {
        return;
      }
      lastUpdate = actualTime;
      //Toast.makeText(this, "Device was shuffed", Toast.LENGTH_SHORT)
         // .show();


      Intent myIntent = new Intent(SensorTestActivity.this, passwordActivity.class);
      startActivity(myIntent);
  }
};

下面是我的完整代码

http://pastebin.com/1WtHYH6z

我很震惊..任何建议表示赞赏。

4

2 回答 2

0

使用字段

int _shaken;

在你的 SensorEvent 中:(我不知道正确的函数名,但我猜你知道..)

OnEvent(){
shaken++;
if(_shaken>=3){
doAction();
_shaken = 0;
}
}
于 2012-11-16T09:45:36.627 回答
0

考虑到 Goot 的回答,您的程序应该类似于:

int count = 0;
private float mAccel; // acceleration apart from gravity
private float mAccelCurrent; // current acceleration including gravity
private float mAccelLast; // last acceleration including gravity

private void getAccelerometer(SensorEvent event) {
    float[] values = event.values;
    // Movement
    float x = values[0];
    float y = values[1];
    float z = 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

    //adjust the mAccel > certain_value (adjust this to change the sensitivity of the       
        //shake) 
    if(mAccel > 5) {
    Toast.makeText(SensorTestActivity.this, "Device is shaking!",      
            Toast.LENGTH_SHORT).show();

        count++;
        if(count >= 3) {
            Intent myIntent = new Intent(SensorTestActivity.this,    
                passwordActivity.class);
            startActivity(myIntent);
            count = 0; //if you want to reset the counter after performing the action
        }
    }
}
于 2012-11-16T12:20:01.720 回答