Java – programmatically lock the direction in Android

I have the following code

Java

public void lockScreenOrientation() {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
}

public void unlockScreenOrientation() {
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}

I call these functions from JavaScript Control is entering these methods But the direction is not locked

I tried to follow the lock direction

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);

None of this seems to work Any pointer will help

Solution

I've created some practical methods to help handle direction locking. Feel free to use this class

Use example:

>In the activity: orientationutils Lockorientationportlet (myactivityname. This) > in the fragment: orientationutils lockOrientationLandscape(getActivity())

Code:

/** Static methods related to device orientation. */
public class OrientationUtils {
    private OrientationUtils() {}

    /** Locks the device window in landscape mode. */
    public static void lockOrientationLandscape(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    /** Locks the device window in portrait mode. */
    public static void lockOrientationPortrait(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    /** Allows user to freely use portrait or landscape mode. */
    public static void unlockOrientation(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    }

}

This is my complete orientationutils class on GitHub, which can be used in any Android Application: https://github.com/danialgoodwin/android-simply-advanced-helper/blob/master/SimplyAdvancedHelperLibrary/src/net/simplyadvanced/utils/OrientationUtils.java

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>