如何在启动应用时获取Android设备方向

时间:2016-09-07 10:43:19

标签: android android-sensors android-orientation device-orientation

我试过这个,不行,我总是有0度

Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenOrientation = display.getRotation();

如果使用SensorManager,它也不起作用,因为如果我不移动手机就不会触发

mOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) {

    @Override
    public void onOrientationChanged(int orientation) {
    }
};

更新

请尝试完整演示

https://github.com/sochap/getorientationquestdemo

由于显示未更改,请使用display确定不可能

我将获得设备方向,而不是显示方向

OrientationEventListener可以使用,但不能在onCreate

3 个答案:

答案 0 :(得分:1)

这可能对你有用。试试这个。

 Configuration config = getResources().getConfiguration();

    if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {

                     // set Values for landscape

 } else if (config.orientation == Configuration.ORIENTATION_PORTRAIT) {

                   // set Values for portrait
    }

答案 1 :(得分:0)

尝试

int currentOrientation = getResources().getConfiguration().orientation;

if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
     //do something
} else {
     //do something
} 

答案 2 :(得分:-1)

使用Activity的onConfigurationChanged方法。请参阅以下代码:

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
   // Checks the orientation of the screen
  if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
    Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
  } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
    Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
  }
}

您还必须编辑清单文件中的相应元素以包含android:configChanges只需看下面的代码:

<activity android:name=".MyActivity"
      android:configChanges="orientation|keyboardHidden"
      android:label="@string/app_name">

注意:对于Android 3.2(API级别13)或更高版本,当设备在纵向和横向之间切换时,“屏幕尺寸”也会发生变化。因此,如果您想在开发API级别13或更高级别时因为方向更改而阻止运行时重新启动,则必须为API级别13或更高级别设置decalare android:configChanges =“orientation | screenSize”。

希望这会对你有所帮助.. :)

相关问题