Only fullscreen activities can request orientation终极解决方法

11 篇文章 0 订阅
@Override
protected void onCreate(Bundle savedInstanceState) {
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
        boolean result = fixOrientation();
        XLog.i(XLog.BASE, "onCreate fixOrientation when Oreo, result = " + result);
    }
    super.onCreate(savedInstanceState);
}

@Override
public void setRequestedOrientation(int requestedOrientation) {
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
        XLog.i(XLog.BASE, "avoid calling setRequestedOrientation when Oreo.");
        return;
    }
    super.setRequestedOrientation(requestedOrientation);
}

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;
}

参考:https://blog.csdn.net/starry_eve/article/details/82777160

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值