Prevent Android from rotating your activity

There are applications in which you want to have your Android's activity to always display in landscape or portrait even if the user rotates the device. To do so, add the android:screenOrientation and android:configChanges attributes of your activity tag in the AndroidManifest.xml file.

Example to keep your activity to always display in portrait:

 1 <activity android:name=".AndroidApplication"
 2           android:label="@string/app_name" 
 3           android:screenOrientation="portrait" 
 4           android:configChanges="keyboardHidden|orientation">
 5     <intent-filter>
 6         <action android:name="android.intent.action.MAIN" />
 7         <category android:name="android.intent.category.LAUNCHER" />
 8     </intent-filter>
 9 </activity>


Line 3, android:screenOrientation="portrait", is telling Android not to rotate this activity but to always display it in portrait orientation. Android will still destroy and re-create this activity if the user rotates the device though it will always be re-created in portrait orientation.

Line 4, android:configChanges="keyboardHidden|orientation", prevents the activity from being recreated. It's telling Android that you will handle the keyboardHidden and orientation changes instead of letting Android handle these and would re-create the activity. If you want to do some processing on those events then you will have to implement the onConfigurationChanged() in your activity Java codes. Else like in my case where I want my activity to continue on what it was doing, just don't implement the onConfigurationChanged().

Note that these settings are for one activity and not the whole application. So if you need to keep orientation fixed for other activities, you will have to set those settings on each of the activities.