设置android:screenOrientation =“sensorLandscape”可防止活动重启

时间:2015-10-10 10:23:03

标签: android

我已将android:screenOrientation="sensorLandscape"添加到我的清单中的某个活动中。并且没有android:configChanges属性。

这对我来说似乎是一个错误,但现在我的活动没有被重新创建,即在设备旋转时没有调用onCreate()

此外,onConfigurationChanged()也未被调用。

删除行android:screenOrientation="sensorLandscape"可解决问题,并按预期重新启动活动。

有人可以确认这是一个错误,并且/或者有解决方法吗?

2 个答案:

答案 0 :(得分:1)

  

有人确认这是一个错误......

这不是错误。这就是他们设计它的方式。根据{{​​3}},来自Google网上论坛的Dianne Hackborn(大约一半):

  

这根本不是配置更改。平台在执行此操作时没有提供任何通知,因为它对应用程序所处的环境是不可见的。

  

......有解决方法吗?

一种可能的解决方法是注册一些传感器来检测方向变化,但这比自方向传感器弃用以来的工作要多一些。您需要磁场传感器和加速度计来取代其功能。 this post演示如何使用这些传感器获取方向值。

答案 1 :(得分:-1)

我通过收听加速计事件并保留字段mCurrentDisplayRotation来解决此问题。要在Activity中添加完整代码才能使其正常运行:

private SensorManager mSensorManager;
private Sensor mAccelerometer;

private int mCurrentDisplayRotation = -1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera );

    mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}

protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}

protected void onPause() {
    super.onPause();
    mSensorManager.unregisterListener(this);
}

public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

public void onSensorChanged(SensorEvent event) {
    int rotation = getWindowManager().getDefaultDisplay().getRotation();
    if (mCurrentDisplayRotation != rotation) {
        mCurrentDisplayRotation = rotation;
        // handle the rotation change here
    }
}