The accepted answer and everything that setRequestedOrientation offers are far from perfect, because as stated in the documentation , calling setRequestedOrientation at runtime can cause activity to restart, which, among other things, affects animation between screens.
If possible, it's best to set your desired orientation in AndroidManifest.xml . But since there is an error that tends to rely on each developer to remember to modify the manifest when adding a new action, this can be done during build by editing the AndroidManifest file during build.
There are a few caveats for editing AndroidManifest in such a way that you need to know about this:
My requirement was to update all actions with a fixed orientation, but only in the release of the assembly . I achieved this with a bit of code in build.gradle , which does a simple line replacement in AndroidManifest (provided that none of the above actions are already specified):
An example solution compatible with Android Studio 3.0 (touching only the actions corresponding to com.mycompany.* ):
android.applicationVariants.all { variant -> variant.outputs.all { output -> if (output.name == "release") { output.processManifest.doLast { String manifestPath = "$manifestOutputDirectory/AndroidManifest.xml" def manifestContent = file(manifestPath).getText('UTF-8') // replacing whitespaces and newlines between `<activity>` and `android:name`, to facilitate the next step manifestContent = manifestContent.replaceAll("<activity\\s+\\R\\s+", "<activity ") // we leverage here that all activities have android:name as the first property in the XML manifestContent = manifestContent.replace( "<activity android:name=\"com.mycompany.", "<activity android:screenOrientation=\"userPortrait\" android:name=\"com.mycompany.") file(manifestPath).write(manifestContent, 'UTF-8') } } } }
An example solution compatible with Android Studio 2.3 (corresponds to all actions, but does not correspond to <activity-alias> elements):
android.applicationVariants.all { variant -> variant.outputs.each { output -> if (output.name == "release") { output.processManifest.doLast { def manifestOutFile = output.processManifest.manifestOutputFile def newFileContents = manifestOutFile.getText('UTF-8') .replaceAll(/<activity(?!-)/, "<activity android:screenOrientation=\"userPortrait\" ") manifestOutFile.write(newFileContents, 'UTF-8') } } } }
I used userPortrait instead of portrait , as I prefer to give the user more flexibility.
The above crashes if you only have options (debug, release). If you have additional tastes, you may need to modify it a bit.
You can remove if (output.name == "release") depending on your needs.