Unable to start activity ComponentInfo{com.cloudcreate.cloudcreateoffice/com.cloudcreate.cloudcreateoffice
.MainActivity}: java.lang.IllegalStateException: Only fullscreen activities can request orientation
// Activity不是透明且没有指定屏幕方向,默认设置为竖屏
if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
// 上边代码修改成:
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
// android8.0要求不能设置全屏透明的Activity横竖屏
fixOrientation();
} else {
// 当前 Activity 不能是透明的并且没有指定屏幕方向,默认设置为竖屏
if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
/**
* 设置竖屏
*/
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;
}
/**
* 是否是全屏或者悬浮
*/
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;
}
/**
* 设置方向的时候:直接不能设置
*/
@Override
public void setRequestedOrientation(int requestedOrientation) {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
return;
}
super.setRequestedOrientation(requestedOrientation);
}
源地址: https://blog.csdn.net/starry_eve/article/details/82777160
网友评论