简体   繁体   中英

Android - Screen Orientation Issue - Need only portrait

My Issue: I want my application to be run in only portrait mode. For this I have to define " android:screenOrientation=portrait " in "AndroidManifest" file for each activity. I don't want to define that line for each activity. So i came up with another solution like creating a subclass of ' Application ' and registering an activity's life cycle and in method " onActivityCreated " i have added line

activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

But now, problem is this "Device autorotation is enabled and currently device position is landscape and when i open my application, every activity initially launched two times." Is there any general solution for this?

Each activity is launched 2 times because it first loads in landscape mode, calls onCreate() and rotates again when it executes screen rotation line of code

activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

The only way around this to mention screenOrientation="portrait" for each activity in your manifest. That is the only way you force the activity to create in the portrait mode to begin with.

You can achieve this for your entire application by following simple way. This will remove the overhead of extending common base class as well as manifest declaration in each activity for Portrait.

For this your application must have a application class. In its onCreate(), when your app starts for first time, you need to register an ActivityLifecycleCallbacks object (API level 14+) to receive notifications of activity lifecycle events.

Above callback give you an opportunity to execute your own code whenever any activity is started (or stopped, or resumed, or whatever). You can use this to setRequestedOrientation() on the newly created activity.

class DummyApp extends Application {

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

    // Register Callback
    registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        }
        // Other method of the ActivityLifecycleCallbacks as well you need to over-ride.
    });

  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM