I have an application that I just would like to use in portrait mode, so I have defined android:screenOrientation="portrait" in the manifest XML. This works OK for the HTC Magic phone (and prevents orientation changes on other phones as well).
But I have a problem with the HTC G1 phone as I open the hardware QWERTY keyboard (not the virtual keyboard). My activity stays in portrait mode, but it seems to get restarted and loses all its states. This does not happen with the HTC Hero version.
My application is quite big, so I don't want it to restart and lose all its states when the keyboard is opened. How can I prevent that?
In OnCreate method of your activity use this code:
Now your orientation will be set to portrait and will never change.
In the AndroidManifest.xml file, for each activity you want to lock add the last
screenOrientation
line:Or android:screenOrientation="landscape".
I've always found you need both
In your androidmanifest.xml file:
or
As said, set
android:configChanges
of your Activity (in manifest file) tokeyboardHidden|orientation
and then:1) Override
onConfigurationChanged()
2) Add this line to your activity's
onCreate()
It's better than add same line to
onConfigurationChanged
, because your app will turn to portrait mode and then back to landscape (it will happen only one time, but it's annoying).Also you can set
android:screenOrientation="nosensor"
for your activity (in manifest). But using this way you're a not able to handle orientation changes at all.To lock the screen by code you have to use the actual rotation of the screen (0, 90, 180, 270) and you have to know the natural position of it, in a smartphone the natural position will be portrait and in a tablet, it will be landscape.
Here's the code (lock and unlock methods), it has been tested in some devices (smartphones and tablets) and it works great.