In addition, the Android Developers guide states that :
[...] you should also explicitly declare that your application requires
either portrait or landscape orientation with the
element. For example, <uses-feature android:name="android.hardware.screen.portrait" />.
You just have to define the property below inside the activity element in your AndroidManifest.xml file. It will restrict your orientation to portrait.
I can see you have accepted an answer which doesn't solve your problem entirely:
android:screenOrientation="portrait"
This will force your app to be portrait on both phones and tablets.
You can have the app forced in the device's "preferred" orientation by using
android:screenOrientation="nosensor"
This will lead to forcing your app to portrait on most phones phones and landscape on tablets.
There are many phones with keypads which were designed for landscape mode. Forcing your app to portrait can make it almost unusable on such devices. Android is recently migrating to other types of devices as well. It is best to just let the device choose the preferred orientation.
I would like to add to Bhavesh's answer. The problem is that if users keep the phone in landscape mode and run the app it will first go to landscape mode since it's based on sensor in manifest and will then immediately switch to portrait mode in phones because of the code in onCreate. To solve this problem below approach worked for me.
1 Declare locked orientation in manifest for activity android:screenOrientation="locked"
2 Check for tablet or phone in actiivty or base activity
override fun onCreate(savedInstanceState: Bundle?) {
//check if the device is a tablet or a phone and set the orientation accordingly
handleOrientationConfiguration()
super.onCreate(savedInstanceState)
}
/**
* This function has to be called before anything else in order to inform the system about
* expected orientation configuration based on if it is a phone or a tablet
*/
private fun handleOrientationConfiguration() {
requestedOrientation = if (UIUtils.isTablet(this).not()) {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
} else {
ActivityInfo.SCREEN_ORIENTATION_SENSOR
}
}
UIUtils.kt
fun isTablet(context: Context): Boolean {
return context.resources.configuration.smallestScreenWidthDp >= 600
}
That's it, it will launch the app in the locked mode so that if you are on phone it will be always portraited and if you are on a tablet it will rotate based on the orientation of the device. This way it will eliminate the issue on phones where it switches between landscape and portrait at the start.