Search code examples
androidbackandroid-orientation

Switch activiy on orientation changed?


How can I switch to another activity when rotating the phone?

My requirements:

  • Activity A and B are portrait only
  • Acitvity L is landscape only
  • When landscape mode of A or B would be displayed, L is started instead. When portrait of L would be displayed, A or B are displayed.

I can create this behaviour, expect for the back button. When it is pressed I'm either getting A/B in landscape or L in portrait, which I want to prevent.

What I'm doing (Activities A & B, but L is similar)

To trigger the activity call on orientation change:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    int newOrientation = newConfig.orientation;
    if (newOrientation == Configuration.ORIENTATION_LANDSCAPE) {
        Intent intent = new Intent(this, ActivityL.class);
        startActivity(intent);
    }

    super.onConfigurationChanged(newConfig);
}

I want something like the following. But manually (re)setting the orientation prevents onConfigurationChanged() from being called at all:

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

    int currentOrientation = this.getResources().getConfiguration().orientation;
    if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
}

On course the same happens if I do it in other lifecycle methods or onCreate(...).

All activities have:

  android:screenOrientation="sensor"

I also tried imitating the orientation change using the rotationg angle, but then the behavior seems mostly random and not even close to the normal orientation change.


Solution

  • I suppose setRequestedOrientation() overrides what I had defined in the AndroidManifest:

    android:screenOrientation="sensor"
    

    I need to reset it to sensor to get the automated orientation changes back:

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        int newOrientation = newConfig.orientation;
        if (newOrientation == Configuration.ORIENTATION_LANDSCAPE) {
            Intent intent = new Intent(this, ActivityL.class);
            startActivity(intent);
        }
        super.onConfigurationChanged(newConfig);
    
        // Reset to sensor:
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    }
    

    I'm a bit surprised that calling it within onConfigurationChanged(..) works, since that method is no longer called by orientation changes. But I guess the configuration is changed in some other way when the activity is resumed(when back button is pressed).