java java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
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"); } } ...... }
void setRequestedOrientation(int requestedOrientation) { if (ActivityInfo.isFixedOrientation(requestedOrientation) && !fullscreen && appInfo.targetSdkVersion >= O_MR1) { throw new IllegalStateException("Only fullscreen activities can request orientation"); } ...... }
@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); ...... }
@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 工具類:java
/** * 針對 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; }
參考:android
https://blog.csdn.net/starry_eve/article/details/82777160
https://zhuanlan.zhihu.com/p/32190223api