简单说说Android G-sensor 的优化

近期在2.2中解决某个G-sensor的Bug的时候,意外的发现2.3其实已经对这类问题进行了优化,借鉴于2.3的源码,给了我不少帮助。2.3中主要是扩展了对旋屏180°的扩展,这个也许对手机来说没什么实际作用,但是对于平板电脑,却意味深长喽!!!

首先是 int getCurrentRotation() ,不仅仅只针对mRotation ,还增加了对lastRotation的考究,单单就是这点,就方便了我们做很多事情,可以很方便的增加很多判断和条件,来达到我们想要实现的目的。代码如下:

int getCurrentRotation(int lastRotation) {
if (mTiltDistrust > 0) {
// we really don't know the current orientation, so trust what's currently displayed
mRotation = SURFACE_TO_INTERNAL_ROTATION[lastRotation];
}
return INTERNAL_TO_SURFACE_ROTATION[mRotation];
}

最值得一提的就是下面的代码了:

// Mapping our internal aliases into actual Surface rotation values
private static final int[] INTERNAL_TO_SURFACE_ROTATION = new int[] {
Surface.ROTATION_0, Surface.ROTATION_90, Surface.ROTATION_270,
Surface.ROTATION_180};

// Mapping Surface rotation values to internal aliases.
private static final int[] SURFACE_TO_INTERNAL_ROTATION = new int[] {
ROTATION_0, ROTATION_90, ROTATION_180, ROTATION_270};

// Threshold ranges of orientation angle to transition into other orientation states.
// The first list is for transitions from ROTATION_0, ROTATION_90, ROTATION_270,
// and then ROTATION_180.
// ROTATE_TO defines the orientation each threshold range transitions to, and must be kept
// in sync with this.
// We generally transition about the halfway point between two states with a swing of 30
// degrees for hysteresis.
private static final int[][][] THRESHOLDS = new int[][][] {
{{60, 180}, {180, 300}},
{{0, 30}, {195, 315}, {315, 360}},
{{0, 45}, {45, 165}, {330, 360}},

// Handle situation where we are currently doing 180 rotation
// but that is no longer allowed.
{{0, 45}, {45, 135}, {135, 225}, {225, 315}, {315, 360}},
};
// See THRESHOLDS
private static final int[][] ROTATE_TO = new int[][] {
{ROTATION_90, ROTATION_270},
{ROTATION_0, ROTATION_270, ROTATION_0},
{ROTATION_0, ROTATION_90, ROTATION_0},
{ROTATION_0, ROTATION_90, ROTATION_0, ROTATION_270, ROTATION_0},
};

// Thresholds that allow all 4 orientations.
private static final int[][][] THRESHOLDS_WITH_180 = new int[][][] {
{{60, 165}, {165, 195}, {195, 300}},
{{0, 30}, {165, 195}, {195, 315}, {315, 360}},
{{0, 45}, {45, 165}, {165, 195}, {330, 360}},
{{0, 45}, {45, 135}, {225, 315}, {315, 360}},
};
// See THRESHOLDS_WITH_180
private static final int[][] ROTATE_TO_WITH_180 = new int[][] {
{ROTATION_90, ROTATION_180, ROTATION_270},
{ROTATION_0, ROTATION_180, ROTATION_90, ROTATION_0},
{ROTATION_0, ROTATION_270, ROTATION_180, ROTATION_0},
{ROTATION_0, ROTATION_90, ROTATION_270, ROTATION_0},
};

注释写的清晰明了,我把它加入到2.2中,稍作修实现了我所想实现的目标,让G-sensor在某种特殊情况x,y,z 重定义N次得情况下,稳定工作。这还是要归功于,GOOGLE在x,y,z三维检测对0,90,180,270,4方向的支持。

另外,这也给大家提个醒,有什么没有解决的bug,不如看看高版本有没有进行优化和改变,也许会有意外收获~

你可能感兴趣的:(android)