刚上班,没有业务开发,对 App 的 Api 由 26 升级到了 27, 结果在 Android 8.0 的设备上会出现 crash 。
-
Log 如下:
java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
经过搜索发现该问题是在 App 适配了 Api 27 ,然后运行设备是 26 的时候出现的。
-
查看源码(Api 27的源码),总共有两个地方会抛出来这个异常:
- Activity 的 onCreate 方法:
protected void onCreate(@Nullable Bundle savedInstanceState) {
if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState); if (getApplicationInfo().targetSdkVersion >= O_MR1 && mActivityInfo.isFixedOrientation()) {
final TypedArray ta = obtainStyledAttributes(com.android.internal.R.styleable.Window);
final boolean isTranslucentOrFloating = ActivityInfo.isTranslucentOrFloating(ta);
ta.recycle(); if (isTranslucentOrFloating) {
throw new IllegalStateException(
"Only fullscreen opaque activities can request orientation");
}
}
......
}- ActivityRecord 的 setRequestedOrientation 方法:
void setRequestedOrientation(int requestedOrientation) {
if (ActivityInfo.isFixedOrientation(requestedOrientation) && !fullscreen
&& appInfo.targetSdkVersion >= O_MR1) {
throw new IllegalStateException("Only fullscreen activities can request orientation");
} ......
} -
解决办法:
- 在 BaseActivity 中的 onCreate 方法进行处理
@Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && UiUtils.isTranslucentOrFloating(this)) {
UiUtils.fixOrientation(this);
KLog.debug("api 26 全屏横竖屏切换 crash");
}
super.onCreate(savedInstanceState);
......
}- 在 BaseActivity 的 setRequestedOrientation 方法中进行处理
@Override
public void setRequestedOrientation(int requestedOrientation) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && UiUtils.isTranslucentOrFloating(this)) {
KLog.debug("api 26 全屏横竖屏切换 crash");
return;
}
super.setRequestedOrientation(requestedOrientation);
} -
UiUtils 工具类:
/**
* 针对 Android 27 的情况进行处理
* 横竖屏设置了方向会崩溃的问题
*
* @return
*/
public static boolean isTranslucentOrFloating(Activity activity) {
boolean isTranslucentOrFloating = false;
try {
int[] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
TypedArray ta = activity.obtainStyledAttributes(styleableRes);
Method m = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
m.setAccessible(true);
isTranslucentOrFloating = (boolean)m.invoke(null, ta);
m.setAccessible(false);
} catch (Exception e) {
e.printStackTrace();
}
return isTranslucentOrFloating;
} /**
* 修复横竖屏 crash 的问题
* @return
*/
public static boolean fixOrientation(Activity activity){
try {
Field field = Activity.class.getDeclaredField("mActivityInfo");
field.setAccessible(true);
ActivityInfo o = (ActivityInfo)field.get(activity);
o.screenOrientation = -1;
field.setAccessible(false);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
} 参考:
https://blog.csdn.net/starry_eve/article/details/82777160
https://zhuanlan.zhihu.com/p/32190223