java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

字面意思就是说:只有不透明的全屏activity可以自主设置界面方向。

这个问题出现在android8.0以上。原因是我们给Activity同时设置了
android:screenOrientation="" 和 true。
解决方法1:在BaseActivit中
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {

    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
        boolean result = fixOrientation();
        Log.e(TAG, "onCreate: "+"onCreate fixOrientation when Oreo, result = " + result );
    }
    super.onCreate(savedInstanceState);

}

private boolean fixOrientation(){
try {
Field field = Activity.class.getDeclaredField(“mActivityInfo”);
field.setAccessible(true);
ActivityInfo o = (ActivityInfo)field.get(this);
o.screenOrientation = -1;
field.setAccessible(false);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

@Override
public void setRequestedOrientation(int requestedOrientation) {
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
        Log.e(TAG, "setRequestedOrientation: "+"avoid calling setRequestedOrientation when Oreo." );
        return;
    }
    super.setRequestedOrientation(requestedOrientation);
}

private boolean isTranslucentOrFloating(){
    boolean isTranslucentOrFloating = false;
    try {
        int [] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
        final TypedArray ta = 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;
}

就可以完美解决问题.

解决办法2:删除AndroidManifest中相应Activity的 android:screenOrientation="“属性;
或者删除相应Activity的theme中true属性。
android:name=“com.zkrj.patient.xindian.ConnectActivity”
android:configChanges="keyboardHidden|orientation"
android:screenOrientation=“portrait”
android:theme=”@style/selectorDialog"/>

< Activity 设置 Dialog >

 

你可能感兴趣的:(日常笔记)