Android设备定位是风景,但传感器的行为就像定位是肖像

gur*_*kan 4 android orientation device-orientation android-sensors

我在android中的方向有问题.设备方向是我在AndroidManifest.xml文件中设置的横向.

android:screenOrientation="landscape"
Run Code Online (Sandbox Code Playgroud)

此外,我在横向上持有设备,所以一切(布局,视图等)都是横向模式,正如我想要的那样.但只有当我以纵向方式握住设备时,它才能为我提供所需的价值.

我修改了一些来自互联网的代码,它适用于HTC 3d EVO,Nexus 7和三星Galaxy S3,但不适用于Galaxy Tablet 10".

我找到了这篇文章. Android方向传感器对于不同设备有何不同? 接受的答案建议使用getRotation()和remapCoordinateSystem()方法,但不提及如何使用.

这就是我的结局.

        SensorManager.getRotationMatrix(Rmat, Imat, gData, mData);
        SensorManager.remapCoordinateSystem(Rmat, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, R2);
        // Orientation isn't as useful as a rotation matrix, but
        // we'll show it here anyway.
        SensorManager.getOrientation(R2, orientation);
        float incl = SensorManager.getInclination(Imat);

        FontTextView pitchText = (FontTextView)findViewById(R.id.pitch_text);

        if((int)(orientation[1]*90) <= -110 && !newQuestionIsActive) {
            newQuestionIsActive = true;
            pitchText.setText("Bring new question");
        }
        else if(Math.abs((int)(orientation[2]*90)) <= 200 && (int)(orientation[1]*90) >= -30 && newQuestionIsActive) {
            newQuestionIsActive = false;
            pitchText.setText("Not Correct!");
        }
        else if(Math.abs((int)(orientation[2]*90)) > 200 && (int)(orientation[1]*90) >= -30 && newQuestionIsActive) {
            newQuestionIsActive = false;
            pitchText.setText("Congratulations!");
        }
Run Code Online (Sandbox Code Playgroud)

现在我该如何在这段代码中使用getRotation()?并且可能是一个简短的解释将被理解为什么那些提到的3设备工作正常但不是Galaxy平板电脑.

关于这个问题android文档说;

最后,如果您的应用程序将传感器数据与屏幕显示匹配,则需要使用getRotation()方法确定屏幕旋转,然后使用remapCoordinateSystem()方法将传感器坐标映射到屏幕坐标.即使您的清单指定仅限纵向显示,您也需要这样做.

http://android-developers.blogspot.com/2010/09/one-screen-turn-deserves-another.html

gur*_*kan 12

找到了解决方案.

问题是由一些较新的设备的默认方向设置为横向而其他人的肖像.因此传感器管理器的行为相应.为了使传感器管理器按预期工作,您需要检测设备的defaultDisplayRotation并更改remapCoordinateSystem()参数逻辑.

我改变了

SensorManager.remapCoordinateSystem(Rmat, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, R2);
Run Code Online (Sandbox Code Playgroud)

int rotation = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
if(rotation == 0) // Default display rotation is portrait
    SensorManager.remapCoordinateSystem(Rmat, SensorManager.AXIS_MINUS_X, SensorManager.AXIS_Y, R2);
else   // Default display rotation is landscape
    SensorManager.remapCoordinateSystem(Rmat, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, R2);
Run Code Online (Sandbox Code Playgroud)

现在它有效......希望这对其他人有用!