gpt4 book ai didi

android - 用加速度计检测旋转

转载 作者:行者123 更新时间:2023-11-30 00:54:46 24 4
gpt4 key购买 nike

我的应用程序方向必须限于纵向。

但我想检测何时在一秒或更短时间内旋转设备两次。

如何在不旋转应用程序的情况下检测到旋转运动?

最佳答案

最后我是这样解决的:

boolean vertical, horizontal;
int rotation;
long t1, t2, t;

@Override
protected void onCreate(Bundle savedInstanceState) {

rotation = -1;

senSensorManager =
(SensorManager)getSystemService(Context.SENSOR_SERVICE);

senAccelerometer =
senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

senSensorManager.registerListener
(this, senAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);

//...
}

@Override
public void onSensorChanged(SensorEvent event) {
Sensor mySensor = event.sensor;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];

if (rotation == 0) {
t1 = System.currentTimeMillis();
}

if (Math.abs(x)>5 && Math.abs(y)<5 && !horizontal) {
vertical = false;
horizontal = true;
rotation++;
Log.d(TAG, "horizontal");
}
if (Math.abs(x)<5 && Math.abs(y)>5 && !vertical) {
vertical = true;
horizontal = false;
rotation++;
Log.d(TAG, "vertical");
}

t2 = System.currentTimeMillis();
t = t2 - t1;
if (t>1000 && rotation<2) {
rotation = 0;
} else if (t<=1000 && rotation==2) {
Log.d(TAG, "Rotated twice in t <= 1000ms");
rotation = 0;
} else if (rotation>2) {
rotation = 0;
}
}
}

关于android - 用加速度计检测旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40362416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com