How to use Android sensor event to determine if device is facing up or down

混江龙づ霸主 提交于 2019-12-04 22:41:00

问题


I have quite a simple requirement. Assuming a device is standing on its end, perpendicular to the ground, and it is tilted, all I need to determine is whether the phone is tilted forward or back (screen more toward the ground or more toward the ceiling).

I know how to read values from the various sensors and I figure that using sensor TYPE_ROTATION_VECTOR is the way forward. All I'm missing is the maths know-how to determine forward or back from the three values it returns.

I've read all related threads on SO without enlightenment, any help very much appreciated.


回答1:


float[] rotationMatrix = new float[9];
float[] inclinationMatrix = new float[9];
float[] accelerometer; // values from sensor
float[] magnetic; // values from sensor
SensorManager.getRotationMatrix(rotationMatrix, inclinationMatrix, accelerometer, magnetic) 
int inclination = (int) Math.round(Math.toDegrees(Math.acos(rotationMatrix[8])));

if (inclination < 90)
{
      // face up
}

if (inclination > 90)
{
       // face down
}



回答2:


The X axis is horizontal and points to the right, the Y axis is vertical and points up and the Z axis points towards the outside of the front face of the screen. In this system, coordinates behind the screen have negative Z values.

The reference coordinate system is defined as a direct orthonormal basis, where:

X is defined as the vector product Y.Z (It is tangential to the ground at the device's current location and roughly points East).
Y is tangential to the ground at the device's current location and points towards magnetic north.
Z points towards the sky and is perpendicular to the ground.

In your case try this,

if(Round(y,4) < 8.0){
           Log.d("sensor", "=====UP====");


        }

        else if(Round(y,4) < -8.0){
            Log.d("sensor", "=====DOWN====");

        }




回答3:


You can use the accelerometer and the magnetic field sensor to detect this.

I've found this helpful blog post which has the necessary code to show you how to do this.

http://www.ahotbrew.com/how-to-detect-forward-and-backward-tilt/



来源:https://stackoverflow.com/questions/14477133/how-to-use-android-sensor-event-to-determine-if-device-is-facing-up-or-down

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!