Android強制設置屏幕旋轉方向 Force rotation


第一種方法:

首先檢查有沒有權限,沒有就去申請。申請時會觸發frameworks/base/services/core/java/com/android/server/wm/AlertWindowNotification.java里面

彈出可以覆蓋view的權限窗口。

檢查和處理的code如下:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            if (!Settings.canDrawOverlays(this))
            {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
                return;
            }
        }
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE)
        {
            if (Settings.canDrawOverlays(this))
            {
                //Already has permission
            }
        }
    }

實際去鎖定旋轉和恢復的code如下:

 
         

public final static int STATE_DEFAULT = 0;
public final static int STATE_PORTRAIT = 1;
public final static int STATE_LANDSCAPE = 8;


WindowManager mWindowManager; View mView; WindowManager.LayoutParams lp; mWindowManager
= (WindowManager) getSystemService(Context.WINDOW_SERVICE); int iFlags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED; lp = new WindowManager.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, iFlags, PixelFormat.TRANSLUCENT ); mView = new View(this);
switch (rotation)
        {
            //Normal Operation
            case MainActivity.STATE_DEFAULT:
                if (mAdded == true) mWindowManager.removeView(mView);
                mAdded = false;
                break;
                
            //Force Rotation
            case MainActivity.STATE_LANDSCAPE:
            case MainActivity.STATE_PORTRAIT:
                lp.screenOrientation = rotation;
                if (mAdded == false)
                {
                    mWindowManager.addView(mView, lp);
                    mAdded = true;
                }else{
                    mWindowManager.updateViewLayout(mView, lp);
                }
                break;
        }

上面的方法在添加system權限后,可以直接獲得權限,不再需要申請。

android:sharedUserId="android.uid.system"

 

第二種方法是仿照SystemUI里面檢查旋轉方向的方式,類似旋轉屏幕后,把auto-rotation disable。

參照frameworks/base/core/java/com/android/internal/view/RotationPolicy.java里面

    /**
     * Returns true if rotation lock is enabled.
     */
    public static boolean isRotationLocked(Context context) {
        return Settings.System.getIntForUser(context.getContentResolver(),
                Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) == 0;
    }

    /**
     * Enables or disables rotation lock from the system UI toggle.
     */
    public static void setRotationLock(Context context, final boolean enabled) {
        Settings.System.putIntForUser(context.getContentResolver(),
                Settings.System.HIDE_ROTATION_LOCK_TOGGLE_FOR_ACCESSIBILITY, 0,
                UserHandle.USER_CURRENT);

        final int rotation = areAllRotationsAllowed(context) ? CURRENT_ROTATION : NATURAL_ROTATION;
        setRotationLock(enabled, rotation);
    }

    private static void setRotationLock(final boolean enabled, final int rotation) {
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    IWindowManager wm = WindowManagerGlobal.getWindowManagerService();
                    if (enabled) {
                            wm.freezeRotation(rotation);
                        } else {
                            wm.thawRotation();
                    }
                } catch (RemoteException exc) {
                    Log.w(TAG, "Unable to save auto-rotate setting");
                }
            }
        });
    }

因為直接用RotationPolicy中public的 setRotationLock(Context, final boolean)只能鎖定當前已經旋轉的屏幕,所以不如直接仿照這個private的

setRotationLock(final boolean, final int)去呼叫

import android.view.IWindowManager;
import android.view.Surface;
import android.view.WindowManagerGlobal;

if(value == LANDSCAPE) {
                AsyncTask.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            IWindowManager wm = WindowManagerGlobal.getWindowManagerService();
                            //if (enabled) {
                                    wm.freezeRotation(Surface.ROTATION_90);
/*                                } else {
                                    wm.thawRotation();
                            }*/
                        } catch (RemoteException exc) {
                            Log.w(TAG, "Unable to save auto-rotate setting");
                        }
                    }
                });
            }else {
                AsyncTask.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            IWindowManager wm = WindowManagerGlobal.getWindowManagerService();
                            wm.thawRotation();
                        } catch (RemoteException exc) {
                            Log.w(TAG, "Unable to save auto-rotate setting");
                        }
                    }
                });
            }

這個需要在源碼里面編譯,不然只能用反射。

 

第三種方法:

1. 修改frameworks/base/core/res/res/values/config.xml中

 

    <bool name="config_deskDockEnablesAccelerometer">false</bool>
    <integer name="config_deskDockRotation">270</integer>

 

其中第一個參數是在有Dock event時候,不使用Accelerometer自動旋轉

第二個參數是在收到Dock event時候, 旋轉屏幕的角度。-1為不旋轉,可以設置為0-360度

 

2. 然后參考https://www.cnblogs.com/kunkka/p/10805388.html里面frameworks的修改

在偵測到有device連接時,去發送DOCK event

連接時:

 

final Intent statusIntent = new Intent(Intent.ACTION_DOCK_EVENT);
             statusIntent.putExtra(Intent.EXTRA_DOCK_STATE,Intent.EXTRA_DOCK_STATE_DESK);
             mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);

 

斷開連接時:

final Intent statusIntent = new Intent(Intent.ACTION_DOCK_EVENT);
             statusIntent.putExtra(Intent.EXTRA_DOCK_STATE,Intent.EXTRA_DOCK_STATE_UNDOCKED);
             mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);

 

此時,在PhoneWindowManager.java中會去讀第一步設定的連接DOCK的config,並listen第二步發送的DOCK event去旋轉屏幕。

PhoneWindowManager里面是android已經做好的DOCK的功能,不需要修改。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM