好的解决了我的问题到一定程度,所以它对我有用,我忽略了自下而上的识别。
public class DeviceOrientation {
public static final int ORIENTATION_PORTRAIT = 0;
public static final int ORIENTATION_LANDSCAPE_REVERSE = 1;
public static final int ORIENTATION_LANDSCAPE = 2;
public static final int ORIENTATION_PORTRAIT_REVERSE = 3;
int smoothness = 1;
public float averagePitch = 0;
public float averageRoll = 0;
public int orientation = ORIENTATION_PORTRAIT;
private float[] pitches;
private float[] rolls;
public DeviceOrientation(int smoothness) {
this.smoothness = smoothness;
pitches = new float[smoothness];
rolls = new float[smoothness];
}
public void addSensorEvent(SensorEvent event) {
azimuth = event.values[0];
averagePitch = addValue(event.values[1], pitches);
averageRoll = addValue(event.values[2], rolls);
orientation = calculateOrientation();
}
private float addValue(float value, float[] values) {
float average = 0;
for(int i=1; i<smoothness; i++) {
values[i-1] = values[i];
average += values[i];
}
values[smoothness-1] = value;
average = (average + value)/smoothness;
return average;
}
/** handles all 4 possible positions perfectly */
private int calculateOrientation() {
// finding local orientation dip
if (((orientation == ORIENTATION_PORTRAIT || orientation == ORIENTATION_PORTRAIT_REVERSE)
&& (averageRoll > -30 && averageRoll < 30))) {
if (averagePitch > 0)
return ORIENTATION_PORTRAIT_REVERSE;
else
return ORIENTATION_PORTRAIT;
} else {
// divides between all orientations
if (Math.abs(averagePitch) >= 30) {
if (averagePitch > 0)
return ORIENTATION_PORTRAIT_REVERSE;
else
return ORIENTATION_PORTRAIT;
} else {
if (averageRoll > 0) {
return ORIENTATION_LANDSCAPE_REVERSE;
} else {
return ORIENTATION_LANDSCAPE;
}
}
}
}
说明:如果我处于纵向模式并将移动设备向前倾斜直到它处于水平位置,由于其余代码,它将切换到横向。因此,我检查它是否是纵向的,并使条件难以离开此模式。这就是我对局部倾角的看法。其余的只是分为所有 3 个方向。
一件事是坏的。如果设备在 Landscape_x 中并向后倾斜一些度数,则 pich 从 ~2 跳到 ~175。那时我的代码在横向和纵向之间翻转。
平滑度将通过组合最后 n 个值并计算平均值来平滑传感器数据的值。这不是真的必要。
我希望这对其他人有帮助。如果您可以进一步改进代码,请告诉我。