Android加速度计稳定性

时间:2015-08-03 07:07:08

标签: android accelerometer

我正在尝试使用accelerometer从面朝下(左,右,右上,上下)四个不同角度检测flipping手机,以及是否快速完成或慢。我还希望在手机flipping大约30度后停止检查。

我的问题是获得一些稳定性。它偶尔会工作,然后无法正常工作。

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    ...

    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

}

@Override
protected void onResume() {
    super.onResume();

    ...

    mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}

@Override
public void onSensorChanged(SensorEvent event) {

    preTS = TS;
    preX = X;
    preY = Y;
    preZ = Z;

    realX = event.values[0];
    realY = event.values[1];
    realZ = event.values[2];

    X = Math.abs(event.values[0]);
    Y = Math.abs(event.values[1]);
    Z = Math.abs(event.values[2]);
    TS = event.timestamp;

    if (X < 2 && Y < 1) {

        npsX = ((TS - preTS) * Math.abs(X - preX)) / 100000;
        npsY = ((TS - preTS) * Math.abs(Y - preY)) / 100000;
        npsZ = ((TS - preTS) * Math.abs(Z - preZ)) / 100000;
    }

    maxX = (maxX > npsX) ? maxX : npsX;
    maxY = (maxY > npsY) ? maxY : npsY;
    maxZ = (maxZ > npsZ) ? maxZ : npsZ;

    if(X < 1 && Y < 1 && Z > 9) {

        maxX = 0;
        maxY = 0;
        maxZ = 0;
        dir = "";
        speed = "";
    }

    if (Objects.equals(dir, "") || Objects.equals(speed, "")) {

        if (realX >= 2) {

            dir = "left";

        } else if (realX <= -2) {

            dir = "right";

        } else if (realY >= 2) {

            dir = "up";

        } else if (realY <= -2) {

            dir = "down";
        }

        if (maxX > 250 || maxY > 250 || maxZ > 250)

            speed = "fast";

        else

            speed = "slow";
    }

    Log.i("MA", (int) maxX + " " + (int) maxY + " " + (int) maxZ + " " + X + " " + Y + " " +
            Z + " " + speed + " " + dir + " " + realX + " " + realY + " " + realZ);

}

0 个答案:

没有答案