首页 > 解决方案 > 如何使系统窗口以传感器纵向模式运行?

问题描述

我试图通过在它们上面绘制一个系统覆盖窗口来强制应用程序以任何所需的方向运行。我无法让它在纵向模式下使用传感器(意味着将其设置为仅自动旋转到纵向或反向纵向)。这是窗口:

WindowManager wm = (WindowManager) this.getSystemService(Service.WINDOW_SERVICE);
View orientationChanger = new LinearLayout(this);

orientationChanger.setClickable(false);
orientationChanger.setFocusable(false);
orientationChanger.setFocusableInTouchMode(false);
orientationChanger.setLongClickable(false);
// Using TYPE_SYSTEM_OVERLAY is crucial to make your window appear on top
// You'll need the permission android.permission.SYSTEM_ALERT_WINDOW
WindowManager.LayoutParams orientationLayout;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    orientationLayout = new WindowManager.LayoutParams(
        WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
        PixelFormat.RGBA_8888
    );
} else orientationLayout = new WindowManager.LayoutParams(
        WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
        PixelFormat.RGBA_8888);
// Use whatever constant you need for your desired rotation
orientationLayout.screenOrientation = rotationSetting.orientation; //rotationSetting is just an object containing the user's desired orientation

wm.addView(orientationChanger, orientationLayout);
orientationChanger.setVisibility(View.VISIBLE);

问题是设置orientationLayout.screenOrientation为与设置ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT为相同ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,这意味着它保持纵向模式并且永远不会旋转到反向纵向。

我尝试了这个值ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,它确实有效,这意味着手机只会自动旋转到横向或反向横向。我也尝试了这个值ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR,这也有效,这意味着手机会在所有 4 个方向上自动旋转,包括反向肖像。所以只有ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT这样是行不通的。知道为什么这个值不起作用吗?

标签: javaandroid

解决方案


推荐阅读