How to lock the app screen oriention at runtime on Android?

Viewed 87

My app follows the screen orientation by default, but I want to add a setting to force a specific orientation. I have been able to do this using the following code in the Application class

    public void applyOrientationMode() {
    final OrientationEnum orientation = PreferencesHelper.getOrientationMode();
    if (this.orientationLifecycleCallback != null) {
        try {
            unregisterActivityLifecycleCallbacks(this.orientationLifecycleCallback);
        } catch (final Throwable t) {
            ExceptionHelper.fullLogging(t, TAG);
        }
    }


    if (orientation != null && orientation != OrientationEnum.UNLOCKED) {
        this.orientationLifecycleCallback = new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle bundle) {
                switch (orientation) {
                    case PORTRAIT:
                        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                        break;
                    case LANDSCAPE:
                        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        break;
                }
            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        };

        registerActivityLifecycleCallbacks(this.orientationLifecycleCallback);
    }
}

This code is called from the application.onCreate() It works fine, however if I set the settings to portrait mode and open a new activity with the screen in landscape I can see th screen created in landscape mode before being recreated in the portrait mode. How I can prevent this?

Please don't use any manifest orientation solution as this is NOT what I'm trying to do

Thanks

0 Answers
Related