如何以编程方式获取 Android 设备方向,api 23+

How to get Android Device's orientation programatically, api 23+

Simple orientation image

如图,我想获取pitch,也就是想检测设备是否与地面平行。

试试这个来获取设备方向

getResources().getConfiguration().orientation

https://developer.android.com/reference/android/content/res/Configuration.html#ORIENTATION_LANDSCAPE

使用下面的代码片段它工作正常...

private boolean isLandscape()
{
return Activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;

}

我这样注册方向:

 sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
 sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);

并将 onSensorChanged 中的值与 phone 与地面平行放置时传感器给出的值进行比较。