I have a CheckBoxPreference with key "allow_reorientation". If enabled then my main activity should reorient upon device rotation, and if disabled it should remain in its current orientation. I have set 'android:configChanges="orientation"' in my manifest.xml to allow custom handling of orientation changes.
From my main activity class:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
if (preferences.getBoolean("allow_reorientation", true)) {
switch(newConfig.orientation) {
case Configuration.ORIENTATION_PORTRAIT:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case Configuration.ORIENTATION_LANDSCAPE:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
default:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
break;
}
}
}
If I start my application in portrait, then rotate the device to landscape, the above code is called and behaves as desired. However, the method is not called at all when rotating back to portrait, and of course the view remains in landscape.
My first guess was that since I don't store the 'newConfig.orientation' anywhere, the second reorientation back to portrait was comparing the latest orientation value against a pre-existing value that still indicated portrait orientation, and thus no configuration change was detected. However, if this were true then a breakpoint I've set in the above method would be activated when I attempt to orient to landscape a second time, yet the method is never called in this circumstance.
Could someone please elucidate what's going on, and offer a remedy?
Many thanks.
SOLUTION - Thanks go to Matthew Willis below
In YourApp which extends Application:
public void updateOrientationConfiguration(Activity activity) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
if (preferences.getBoolean("allow_reorientation", true)) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
} else {
if (activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
if (activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
}
In YourActivity which extends Activity:
public void onResume() {
super.onResume();
YourApp app = (YourApp)this.getApplication();
app.updateOrientationConfiguration(this);
}