From the documentation of setRequestedOrientation
:
public void setRequestedOrientation (int requestedOrientation)
Change the desired orientation of this activity.
If the activity is currently in the foreground or otherwise impacting
the screen orientation, the screen will immediately be changed
(possibly causing the activity to be restarted). Otherwise, this will
be used the next time the activity is visible.
So it should work as you describe, I just tested it and I don't run into any problems or errors. The error must be somewhere else.
The error could also be here:
switch (sharedPrefSettings.getString(SettingsActivity.KEY_PREF_SCREEN_ORIENTATION, "0")) {
case "0":
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
break;
case "1":
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case "2":
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
}
You are using switch on a String
. Until recently that was not supported in Android. Either you have to be sure that your language level is set to 1.7 or you can use Integers
or if statements instead:
switch (sharedPrefSettings.getInt(SettingsActivity.KEY_PREF_SCREEN_ORIENTATION, -1)) {
case 1:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case 2:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
default:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
break;
}
Also you can use default
like I just did to create a safer and more general logic.
The error could also possibly be here:
sharedPrefSettings = PreferenceManager.getDefaultSharedPreferences(this);
getDefaultSharedPreferences()
is potentially dangerous and you should avoid using this instead create your SharedPreferences
explicitly like this:
sharedPrefSettings = getSharedPreferences("settings", MODE_PRIVATE);
So in the end when all mistakes are fixed your code should look like this:
sharedPrefSettings = getSharedPreferences("settings", MODE_PRIVATE);
switch (sharedPrefSettings.getInt(SettingsActivity.KEY_PREF_SCREEN_ORIENTATION, -1)) {
case 1:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case 2:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
default:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
break;
}