android中如何让设配开启横竖屏

最近加入了新的需求,所以工作状态一直都是不停地改BUG改BUG改BUG,发现很多新的东西,可惜根本没有时间记录下来,现在正好闲下来了,刚好可以总结前段时间发现的一些有意思的东西。

我们都知道如何在清单文件中定义一个APP的横屏还是纵屏,无非是
android:screenOrientation="portrait"<!-- 应用纵向 -->
android:screenOrientation="landscape"<!-- 应用横屏 -->
当然,这只是设置一个应用的横向和纵向,现在有个需求是,这个App来自第三方,横纵向可变化,无法修改它的清单文件,所以想控制它的横纵向只能想办法设置手机设备为不可旋转

查看源码可以发现在external/robolectric/v3/runtime/android-all-5.1.1_r9-robolectric-1.jar/com/adnroid/internal/view/menu/RotationPolicy.class中有一个方法为setRotationLock可以操作设备的横纵屏

public static void setRotationLock(Context context, boolean enabled) {
       System.putIntForUser(context.getContentResolver(),   "hide_rotation_lock_toggle_for_accessibility", 0, -2);
    int rotation = areAllRotationsAllowed(context)?-1:0;
    setRotationLock(enabled, rotation);
} 

由上述代码可以看出引用此方法需要两个参数,一个是Context,一个是保存当前旋转方向的布尔值enable
具体操作在下面的代码中:

private static void setRotationLock(final boolean enabled, final int rotation) {
    AsyncTask.execute(new Runnable() {
        public void run() {
            try {
            IWindowManager exc = WindowManagerGlobal.getWindowManagerService();
                if(enabled) {
                    //保持当前旋转方向
                    exc.freezeRotation(rotation);
                } else {
                    //自由转换方向
                    exc.thawRotation();
                }
            } catch (RemoteException var2) {
                Log.w("RotationPolicy", "Unable to save auto-rotate setting");
              }

        }
    });
}

所以我们可以在普通的代码中如此引用:

import com.android.internal.view.RotationPolicy;    
......
代码省略
......
RotationPolicy.setRotationLock(mContext, true);

这样就可以在无法操作此应用时操作设备横纵屏达到控制的效果了

发布了45 篇原创文章 · 获赞 23 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/Easyhood/article/details/72965996