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属性。
<activity
android:name=“com.zkrj.patient.xindian.ConnectActivity”
android:configChanges="keyboardHidden|orientation"
android:screenOrientation=“portrait”
android:theme=”@style/selectorDialog"/>
< Activity 设置 Dialog >
<style name="selectorDialog" parent="@android:style/Theme.Dialog">
<!-- 边框 -->
<item name="android:windowFrame">@null</item>
<!-- 是否浮现在activity之上 -->
<item name="android:windowIsFloating">true</item>
<!-- 半透明 -->
<!--<item name="android:windowIsTranslucent">false</item>-->
<!-- 无标题 -->
<item name="android:windowNoTitle">true</item>
<!-- 背景 -->
<!-- <item name="android:windowBackground">@drawable/selector_dialog_bg</item> -->
<!--是否模糊-->
<item name="android:backgroundDimEnabled">true</item>
<!-- 模糊 -->
<item name="android:backgroundDimAmount">0.5</item>
</style>