How to set entire application in portrait mode only?

For any Android version

From XML

You can specify android:screenOrientation="portrait" for each activity in your manifest.xml file. You cannot specify this option on the application tag.

From Java

Other option is to do it programmatically, for example in an Activity base class:

@Override
public void onCreate(Bundle savedInstanceState) {
  setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

For Android 4+ (API 14+)

Last option is to do it with activity lifecycle listeners which is only available since Android 4.0 (API 14+). Everything happens in a custom Application class:

@Override
public void onCreate() {
    super.onCreate();  
    registerActivityLifecycleCallbacks(new ActivityLifecycleAdapter() {
        @Override
        public void onActivityCreated(Activity a, Bundle savedInstanceState) {
            a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    });
}

ActivityLifecycleAdapter is just a helper class you'll need to create which will be an empty implementation of ActivityLifecycleCallbacks (so you don't have to override each and every methods of that interface when you simply need one of them).


You can do this for your entire application without having to make all your activities extend a common base class.

The trick is first to make sure you include an Application subclass in your project. In its onCreate(), called when your app first starts up, you register an ActivityLifecycleCallbacks object (API level 14+) to receive notifications of activity lifecycle events.

This gives you the opportunity to execute your own code whenever any activity in your app is started (or stopped, or resumed, or whatever). At this point you can call setRequestedOrientation() on the newly created activity.

class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();  

        // register to be informed of activities starting up
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

            @Override
            public void onActivityCreated(Activity activity, 
                                          Bundle savedInstanceState) {

                // new activity created; force its orientation to portrait
                activity.setRequestedOrientation(
                    ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

            }

            ....

        });

    }
}

Yes you can do this both programmatically and for all your activities making an AbstractActivity that all your activities extends.

public abstract class AbstractActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
}

This abstract activity can also be used for a global menu.

Tags:

Android