关于8.0以下出现Only fullscreen opaque activities can request orientation问题的解决方案

原因:

出现Only fullscreen opaque activities can request orientation这个问题是因为8.0之前全屏不透明活动不可以请求方向 要不然只能设置不透明,你看看这扯淡不,我要是不设置透明我还会碰见这种情况? 那么有没有办法解决呢? 那肯定是有的

解决方案:

优雅的方式:Hook反射绕过检查

听起来是不是很cool

思路:

判断是否透明色或者悬浮
修改activity的屏幕方向,不固定,绕过检查。

public class ActivityHook {


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

* 修复android 8.0存在的问题 *

* 在Activity中onCreate()中super之前调用 * * @param activity */ public static void hookOrientation(Activity activity) { //目标版本8.0及其以上 if (activity.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O) { if (isTranslucentOrFloating(activity)) { fixOrientation(activity); } } } /** * 设置屏幕不固定,绕过检查 * * @param activity */ private static void fixOrientation(Activity activity) { try { Class activityClass = Activity.class; Field mActivityInfoField = activityClass.getDeclaredField("mActivityInfo"); mActivityInfoField.setAccessible(true); ActivityInfo activityInfo = (ActivityInfo) mActivityInfoField.get(activity); //设置屏幕不固定 activityInfo.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; } catch (Exception e) { e.printStackTrace(); } } /** * 检查屏幕 横竖屏或者锁定就是固定 * * @param activity * @return */ private static boolean isTranslucentOrFloating(Activity activity) { boolean isTranslucentOrFloating = false; try { Class styleableClass = Class.forName("com.android.internal.R$styleable"); Field WindowField = styleableClass.getDeclaredField("Window"); WindowField.setAccessible(true); int[] styleableRes = (int[]) WindowField.get(null); //先获取到TypedArray final TypedArray typedArray = activity.obtainStyledAttributes(styleableRes); Class ActivityInfoClass = ActivityInfo.class; //调用检查是否屏幕旋转 Method isTranslucentOrFloatingMethod = ActivityInfoClass.getDeclaredMethod("isTranslucentOrFloating", TypedArray.class); isTranslucentOrFloatingMethod.setAccessible(true); isTranslucentOrFloating = (boolean) isTranslucentOrFloatingMethod.invoke(null, typedArray); } catch (Exception e) { e.printStackTrace(); } return isTranslucentOrFloating; } }

在需要的Activity中使用

 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
         
         ActivityHook.hookOrientation(this);//hook,绕过检查
         
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xxxx);

    }

试一下,是不是问题就解决了呢 尿啊~~
大家快去解决问题吧!

你可能感兴趣的:(关于8.0以下出现Only fullscreen opaque activities can request orientation问题的解决方案)