How to detect exact orientation of device in Froyo?

后端 未结 5 1781
执念已碎
执念已碎 2021-01-15 05:18

I\'m trying to temporarily lock the orientation of the Android device, where most of the time it changes with the sensor. So what I want to do is figure out what the current

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-15 06:18

    I modified diyism's answer in a different post to work for Froyo. Since Froyo doesn't support reverse_landscape it will appear upside down but will return to the proper orientation after you unlock. In Gingerbread and later it should work without problems.

    Not a perfect solution but good enough for my needs.

    public static void disableRotation(Activity activity)
    {       
        final int orientation = activity.getResources().getConfiguration().orientation;
        final int rotation = activity.getWindowManager().getDefaultDisplay().getOrientation();
    
        // Copied from Android docs, since we don't have these values in Froyo 2.2
        int SCREEN_ORIENTATION_REVERSE_LANDSCAPE = 8;
        int SCREEN_ORIENTATION_REVERSE_PORTRAIT = 9;
    
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO)
        {
            SCREEN_ORIENTATION_REVERSE_LANDSCAPE = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            SCREEN_ORIENTATION_REVERSE_PORTRAIT = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        }
    
        if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90)
        {
            if (orientation == Configuration.ORIENTATION_PORTRAIT)
            {
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
            else if (orientation == Configuration.ORIENTATION_LANDSCAPE)
            {
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        }
        else if (rotation == Surface.ROTATION_180 || rotation == Surface.ROTATION_270) 
        {
            if (orientation == Configuration.ORIENTATION_PORTRAIT) 
            {
                activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_PORTRAIT);
            }
            else if (orientation == Configuration.ORIENTATION_LANDSCAPE) 
            {
                activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
            }
        }
    }
    
    public static void enableRotation(Activity activity)
    {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    }
    

提交回复
热议问题