I'm developing a mobile application based on Android with minSdkVersion=15
. I would like to support both orientations for tablets and only portrait for smartphones. Everything works like a charm but I'm experiencing a little bug that is driving me crazy. When smartphone is in landscape mode and I try to trigger a new Activity, it opens in landscape mode for a while and then autorotates to portrait. Each one of my activities extend a GeneralActivity class:
public class GeneralActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // If smartphone lock orientation to portrait if (!Helper.isTablet(this.getApplicationContext())){ this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } }
I detect tablets with this function:
public class Helper { public static boolean isTablet(Context context){ Configuration config = context.getResources().getConfiguration() return config.smallestScreenWidthDp >= 600; } }
I choose not to specify android:screenOrientation
inside Manifest.xml because in that way I'm able to support all interface orientation for tablets. Am I missing something?
EDIT
I decided to apply the best practice suggested in the answer by Jonathan, but the issue I described is still here. Here's my repo on github: https://github.com/giacmarangoni/Android-Orientation-Test
If you want the activity to not restart during screen orientation change, you can use the below AndroidManifest. xml. Please note the activity android:configChanges=”orientation|screenSize” attribute. This attribute makes the activity not restart when change screen orientation.
When the screen orientation of an Android device is changed, the current activity being displayed is destroyed and re-created automatically to redraw its content in the new orientation. In other words, the onCreate() method of the activity is fired whenever there is a change in screen orientation.
Background. When you rotate your device and the screen changes orientation, Android usually destroys your application's existing Activities and Fragments and recreates them. Android does this so that your application can reload resources based on the new configuration.
I had the same problem on Android N & O and found a solution.
I still use setRequestedOrientation in the onCreate method, but I've added this for every activity in the manifest:
android:screenOrientation="behind"
This makes sure that the activity launches with the same orientation as the previous activity. The setRequestedOrientation afterwards will override it, but if it's the same as the previous activity you don't see anything change as the user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With