在发布问题之前大量搜索后,我终于基于此贴找到了一个解决方案。我简单地检查当前方向并将其与先前状态进行比较。
getResources().getConfiguration().orientation
如果不同,活动将由于旋转而重新启动。
示例解决方案
我首先有两个成员变量来跟踪以前的配置和标记旋转:
private int previousOrientation = Configuration.ORIENTATION_UNDEFINED
private boolean rotating = false
当活动启动时,在onCreate中,我调用checkAndSetOrientationInfo(),其定义如下:
private void checkAndSetOrientationInfo() {
int currentOrientation = getResources().getConfiguration().orientation;
debugDescribeOrientations(currentOrientation);
if(previousOrientation != Configuration.ORIENTATION_UNDEFINED
&& previousOrientation != currentOrientation) rotating = true;
previousOrientation = currentOrientation;
}
支持的功能包括:
private String getOrientationAsString(final int orientation) {
if(orientation == Configuration.ORIENTATION_LANDSCAPE) {
return "Landscape";
} else if(orientation == Configuration.ORIENTATION_PORTRAIT) {
return "Portrait";
} else return "Undefined";
}
private void debugDescribeOrientations(final int currentOrientation) {
Log.v("Orientation", "previousOrientation: " + getOrientationAsString(previousOrientation));
Log.v("Orientation", "currentOrientation: " + getOrientationAsString(currentOrientation));
}
最后,对于onPause:
@Override
protected void onPause() {
super.onPause();
if (isFinishing()) {
Log.v("onPause", "Finishing");
} else {
checkAndSetOrientationInfo();
if (rotating) {
Log.v("onPause", "Rotating");
} else {
Log.v("onPause", "Not rotating (task switch / home etc)");
}
}
}
我提出并回答了这个问题,以帮助其他遇到同样问题的人。我也很想看到有关这段代码可能失败或其他更好解决方案的评论。
android:configChanges="orientation|keyboard|keyboardHidden"
,这样Android就会在不销毁您的活动的情况下调用onConfigurationChanged()
。然后您可以自己处理配置更改。 - David Wasser