Android:SensorEventListener的时间戳

时间:2012-11-16 09:37:50

标签: android android-sensors

当我摇动设备时,我使用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

我很震惊......很多建议值得赞赏。

2 个答案:

答案 0 :(得分:0)

使用字段

int _shaken;
SensorEvent中的

:  (我不知道正确的functionName,但我猜你做..)

OnEvent(){
shaken++;
if(_shaken>=3){
doAction();
_shaken = 0;
}
}

答案 1 :(得分: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
        }
    }
}