如何在Android中移动摇动时获得时差?

时间:2012-12-06 07:38:45

标签: android

我的问题是如何在Android中使用加速度计来摇动手机之间的持续时间。我的默认阈值为800,速度计算公式为:

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

在这里,我希望在第一次摇晃和下一次摇晃之间获得持续时间。如果持续时间超过10秒,则意味着必须生成警报。

我不知道如何计算传感器概念中的时间间隔。请帮帮我。

感谢。

3 个答案:

答案 0 :(得分:0)

只需使用System.currentTimeMillis()获取第一次摇动的时间并将其保存到某个变量说preTime,当用户再次摇晃时,您可以简单地减去时间差{{1} }

现在如果diffTime = System.currentTimeMillis() - preTime的值再进行剩余的计算

答案 1 :(得分:0)

检查您的手机旋转,您可以使用加速计传感器,

http://www.techrepublic.com/blog/app-builder/a-quick-tutorial-on-coding-androids-accelerometer/472

但您需要使用此传感器检查完整旋转并增加旋转值

答案 2 :(得分:0)

    private static final int FORCE_THRESHOLD = 800;
    private static final int TIME_THRESHOLD = 100;
    private static final int SHAKE_TIMEOUT = 500;
    private static final int SHAKE_DURATION = 1000;
    private static final int SHAKE_COUNT = 3;
    private float mLastX=-1.0f, mLastY=-1.0f, mLastZ=-1.0f;
    private long mLastTime;
    private Context mContext;
    private int mShakeCount = 0;
    private long mLastShake;
    private long mLastForce;



    public void onSensorChanged(SensorEvent event) {
                                if(event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) return;

    Log.v("sensor","sensor change is verifying");
    long now = System.currentTimeMillis();

    if ((now - mLastForce) > SHAKE_TIMEOUT) {
        mShakeCount = 0;
    }

    if ((now - mLastTime) > TIME_THRESHOLD) {
      long diff = now - mLastTime;
      float speed = Math.abs(event.values[SensorManager.DATA_X] + event.values[SensorManager.DATA_Y] + event.values[SensorManager.DATA_Z] - mLastX - mLastY - mLastZ) / diff * 10000;
      if (speed > FORCE_THRESHOLD) {
        if ((++mShakeCount >= SHAKE_COUNT) && (now - mLastShake > SHAKE_DURATION)) 
        {
           mLastShake = now;
           mShakeCount = 0;
            //call the reaction you want to have happen
            onShake();
         }
         mLastForce = now;
       }
         mLastTime = now;
         mLastX = event.values[SensorManager.DATA_X];
         mLastY = event.values[SensorManager.DATA_Y];
         mLastZ = event.values[SensorManager.DATA_Z];
      }
  }