How do I disable orientation change on Android? - android

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?

Update April 2013: Don't do this. It wasn't a good idea in 2009 when I first answered the question and it really isn't a good idea now. See this answer by hackbod for reasons:
Avoid reloading activity with asynctask on orientation change in android
Add android:configChanges="keyboardHidden|orientation" to your AndroidManifest.xml. This tells the system what configuration changes you are going to handle yourself - in this case by doing nothing.
<activity android:name="MainActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation">
See Developer reference configChanges for more details.
However, your application can be interrupted at any time, e.g. by a phone call, so you really should add code to save the state of your application when it is paused.
Update: As of Android 3.2, you also need to add "screenSize":
<activity
android:name="MainActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">
From Developer guide Handling the Configuration Change Yourself
Caution: Beginning with Android 3.2 (API level 13), the "screen size"
also changes when the device switches between portrait and landscape
orientation. Thus, if you want to prevent runtime restarts due to
orientation change when developing for API level 13 or higher (as
declared by the minSdkVersion and targetSdkVersion attributes), you
must include the "screenSize" value in addition to the "orientation"
value. That is, you must declare
android:configChanges="orientation|screenSize". However, if your
application targets API level 12 or lower, then your activity always
handles this configuration change itself (this configuration change
does not restart your activity, even when running on an Android 3.2 or
higher device).

You need to modify AndroidManifest.xml as Intrications (previously Ashton) mentioned and make sure the activity handles the onConfigurationChanged event as you want it handled. This is how it should look:
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

I've always found you need both
android:screenOrientation="nosensor" android:configChanges="keyboardHidden|orientation"

As said, set android:configChanges of your Activity (in manifest file) to keyboardHidden|orientation and then:
1) Override onConfigurationChanged()
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
//here you can handle orientation change
}
2) Add this line to your activity's onCreate()
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
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.

Use this..
android:screenOrientation="portrait"

In OnCreate method of your activity use this code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
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:
android:label="#string/app_name"
android:name=".Login"
android:screenOrientation="portrait" >
Or android:screenOrientation="landscape".

In your androidmanifest.xml file:
<activity android:name="MainActivity" android:configChanges="keyboardHidden|orientation">
or
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

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.
public static void lockScreenOrientation(Activity activity)
{
WindowManager windowManager = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
Configuration configuration = activity.getResources().getConfiguration();
int rotation = windowManager.getDefaultDisplay().getRotation();
// Search for the natural position of the device
if(configuration.orientation == Configuration.ORIENTATION_LANDSCAPE &&
(rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) ||
configuration.orientation == Configuration.ORIENTATION_PORTRAIT &&
(rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270))
{
// Natural position is Landscape
switch (rotation)
{
case Surface.ROTATION_0:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case Surface.ROTATION_90:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
break;
case Surface.ROTATION_180:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
break;
case Surface.ROTATION_270:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
}
}
else
{
// Natural position is Portrait
switch (rotation)
{
case Surface.ROTATION_0:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case Surface.ROTATION_90:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case Surface.ROTATION_180:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
break;
case Surface.ROTATION_270:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
break;
}
}
}
public static void unlockScreenOrientation(Activity activity)
{
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}

Add
android:configChanges="keyboardHidden|orientation|screenSize"
to your manifest.

In Visual Studio Xamarin:
Add:
using Android.Content.PM; to you activity namespace list.
Add:
[Activity(ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)]
as an attribute to you class, like that:
[Activity(ScreenOrientation = ScreenOrientation.Portrait)]
public class MainActivity : Activity
{...}

You can simply use like below in the application class if you want only PORTRAIT mode for all activities in your app.
class YourApplicationName : Application() {
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
override fun onActivityStarted(activity: Activity) {
}
override fun onActivityResumed(activity: Activity) {
}
override fun onActivityPaused(activity: Activity) {
}
override fun onActivityStopped(activity: Activity) {
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
}
override fun onActivityDestroyed(activity: Activity) {
}
})
}
}

Please note, none of the methods seems to work now!
In Android Studio 1 one simple way is to add
android:screenOrientation="nosensor".
This effectively locks the screen orientation.

Related

Android: How to force reverse portrait orientation even if the device auto-rotate screen is off?

I'm working on an app/game that should switch between portrait and reversePortrait in multiplayer mode. (Mainly because each player might use the keyboard on his/her turn while the device is fixed on the table between them.)
My app works fine when the auto-rotate is ON.. But the reversePortrait orientation is NEVER achievable when the device auto-rotate is OFF!
What I did so far is that I've set the orientation in the Manifest file:
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
then I change the orientation programmatically in runtime by calling this method when needed:
public void rotateScreen(boolean reverse){
if (reverse) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
}
else{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
But that still doesn't force to reversePortrait orientation if the device auto-rotation is OFF.
I also tried theonConfigurationChanged() method, but it didn't work as well. I think it only gets called AFTER changing the orientation already, not before!
I even tried screenOrientation="reversePortrait" in the Manifest file, but even that is ineffective when auto-rotation is OFF.
I don't know what exactly you want to achieve. Call your method in OnConfigurationChanged
#Override
public void onConfigurationChanged(Configuration newConfig) {
rotateScreen(true);
super.onConfigurationChanged(newConfig);
}
but here once first launch the screen is reversed but you can apply this as per your requirements.
Please provide more details what you want to achive
After lots of researching, seems that the only way to override the device locked orientation and set the screen to a reverse portrait orientation is to force-enabling the device auto-rotate.
first, must add this permission in the manifest file above the tag:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
then, define something like that in the mainActivity:
public boolean enableAutoRotate(){
boolean isAutoRotate = android.provider.Settings.System
.getInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 1) == 1;
if (!isAutoRotate){
try {
android.provider.Settings.System
.putInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 1);
} catch (Exception e){
e.printStackTrace();
}
}
isAutoRotate = android.provider.Settings.System
.getInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 1) == 1;
return isAutoRotate;
}
The try and catch is important to prevent the app from crashing if the user didn't give or removed the permission.
then, set the orientation when needed using something like this:
public void rotateScreen(boolean reverse){
if (enableAutoRotate()){
if (reverse) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
}
else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
}
rotateScreen method can also be boolean instead of void, if needed.

How to lock screen rotation in the code on Android 4.2 and lower?

I have used ActivityInfo.SCREEN_ORIENTATION_LOCKED and ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED to control screen rotation in Android 4.4,it is good.But when I set the ActivityInfo.SCREEN_ORIENTATION_LOCKED in Android 4.2 ,it is useless.
How can I do it?
You have to declare in your manifest
<activity android:name=".MyActivity"
android:label="#string/app_name"
android:screenOrientation="portrait">
also you can use android:screenOrientation="landscape"
And in your code something like
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Also you can see this guide.
You'll have to override it programatically. Get the current orientation, then if you toggle to fix the state, set that orientation as your application's orientation.
For Example:
int rotation=getResources().getConfiguration().orientation;
//ORIENTATION_LANDSCAPE = 2, ORIENTATION_PORTRAIT=1
if(rotation==1){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}else{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
This will lock it to the current orientation.
And in order to release it, simply use ActivityInfo.SCREEN_ORIENTATION_SENSOR like this:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
That's it.
Now, the final code will look something like this:
if(allow_screen_change.equals("yes")){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}else if(allow_screen_change.equals("no")){
int rotation=getResources().getConfiguration().orientation;
//ORIENTATION_LANDSCAPE = 2, ORIENTATION_PORTRAIT=1
if(rotation==1){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}else{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
I just made this and tested on HTC One X, running Android 4.2 and it works just fine. Hope it helps!

how to prevent game restart when change orientation in AndEngine

i am developing a game in which i have to use both landscape mode for my game scene.
but when i change orientation my game restart and load from splash screen how to stop this.
could any one please help me.
i am using
final EngineOptions eo = new EngineOptions(true, ScreenOrientation.LANDSCAPE_SENSOR,
new FillResolutionPolicy(), _camera);
http://developer.android.com/guide/topics/resources/runtime-changes.html. Please check the documentation under the heading Handling the Configuration Change Yourself.
<activity android:name=".Activity_name"
android:configChanges="orientation|keyboardHidden|screenSize">
Screen size to be added for 3.2 and above.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
//do something
}
else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//do something
}
}
I assume you have a splash screen and after displaying splash screen navigates to activity called Main. In this case your splash screen should run only once when the app is started. You have to call finish() before navigating to next activity. Splash Screen gets destroyed and you navigate to next screen.
add following in your manifest file in your activity tag
android:ConfigChanges="keyboardHidden|orientation|screensize"
add screenOrientation tag in your GameActivity in AndroidManifest.xml
<activity
android:name=".YourgameActivity"
android:screenOrientation="landscape" >
</activity>

How to use onConfigurationChanged() and newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE in android 2.3.3

I am using onConfigurationChanged(). In that, when I am changing from LandScape to Portrait, it is calling if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) and shifting to Portrait from LandScape. But when I am changing from Portrait to Land-Scape, it is not changing to LandScape because it is calling if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) so, it is not changing from LandScape to Portrait.
Please help.
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
//int orientation = this.getResources().getConfiguration().orientation;
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Log.d("Entered to change as Portrait ","PPPPPPPPPPPPPPPPP");
setContentView(R.layout.settings);
} else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Log.d("Entered to change as LandScape ","LLLLLLLLLLLLLLLLLLLL");
setContentView(R.layout.settings);
}
}
Just write the below code into onConfigurationChanged method and test
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
Log.e("On Config Change","LANDSCAPE");
}else{
Log.e("On Config Change","PORTRAIT");
}
and write the android:configChanges="keyboardHidden|orientation" into your manifiest file like this
<activity android:name="TestActivity"
android:configChanges="keyboardHidden|orientation">
it's working at my side, i hope it helps you.
If you're on tablet also add |screenSize to android:configChanges
you should also be aware of:
Caution: Beginning with Android 3.2 (API level 13), the "screen size"
also changes when the device switches between portrait and landscape
orientation. Thus, if you want to prevent runtime restarts due to
orientation change when developing for API level 13 or higher (as
declared by the minSdkVersion and targetSdkVersion attributes), you
must include the "screenSize" value in addition to the "orientation"
value. That is, you must decalare
android:configChanges="orientation|screenSize". However, if your
application targets API level 12 or lower, then your activity always
handles this configuration change itself (this configuration change
does not restart your activity, even when running on an Android 3.2 or
higher device).
The issue is with the android:configChanges="orientation|keyboardHidden" .
if you remove |keyboardHidden from the androidmanifest.xml, then the onConfigurationChanged is only fired when you rotate from landscape to portrait, not when you go from portrait to landscape (at least in the default emulator).
Hope this helps.
In addition to above answers: If you override the onConfigurationChanged method in combination with the updating of the manifest file you are saying you are handling the configurationchanges yourself. Therefore adding:
setContentView(R.layout.layout.xml);
In your onConfigurationChanged method - where layout is your layout file - will fix the problem.
Write below code in your activity file.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
Log.e("On Config Change","LANDSCAPE");
}
else{
Log.e("On Config Change","PORTRAIT");
}
}
Also write below code in your manifest file as follows:
<activity
android:name=".activities.TestActivity"
android:configChanges="orientation|screenSize|keyboardHidden"
/>
Write this line in the android Manifest.xml file:
<activity
android:name="MyActivity"
android:configChanges="orientation|keyboardHidden" />

orientation is not working in 2.3.3?

I have prepared one application.My application will be supports both landscape and portrait.
When i change the orientation from portrait to landscape it is working fine,But when i change landscape to portrait it is not working.my code is,
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
System.out.println("orientation---"+getResources().getConfiguration().orientation);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setContentView(R.layout.main);
System.out.println("landscape-----");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.main);
System.out.println("portrait-----");
}
}
Every time time it taking only landscape mode.I made mistake some where. please help.
System.out.println("orientation---"+getResources().getConfiguration().orientation);
The above SOP is printing 2 means landscape.Please help me.(i am using 2.3.3)
You might be hitting this bug "Orientation does not change from landscape to portrait on Emulator on 2.3"
More than 45 people are facing the same issue with the androidd 2.3 emulator
http://code.google.com/p/android/issues/detail?id=13189
Host OS: Windows 7 SDK tools version : revision 8 Eclipse version: 3.5
ADT plug-in version: 8.0.1 Platform targeted by your project: 2.3
Version of the platform running in the emulator:2.3
STEPS TO REPRODUCE:
1. Activity 1 (no screen orientation) - Activity 2 (screen orientation = landscape)
Going from Activity 1 to 2 works fine. Pressing back changes the orientation of Activity 1 to landscape
EXPECTED RESULTS: Activity 1 should be in portrait mode
OBSERVED RESULTS: Behavior is observed only in gingerbread, works as
expected on froyo.
The issue is with the android:configChanges="orientation|keyboardHidden" .
if you remove |keyboardHidden from the androidmanifest.xml, then the onConfigurationChanged is only fired when you rotate from landscape to portrait, not when you go from portrait to landscape (at least in the default emulator).
Hope this helps.
EDIT: DID some sample program to test it and works fine for me.
CheckOrientationActivity.java
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class CheckOrientationActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
Log.i("DayElevenActivity", "onCreate Start");
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.i("DayElevenActivity", "onConfigurationChanged");
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Log.i("ORIENTATION_LANDSCAPE", "ORIENTATION_LANDSCAPE");
Toast.makeText(getBaseContext(), "ORIENTATION_LANDSCAPE", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Log.i("ORIENTATION_PORTRAIT", "ORIENTATION_PORTRAIT");
Toast.makeText(getBaseContext(), "ORIENTATION_PORTRAIT", Toast.LENGTH_SHORT).show();
}
}
}
In AndroidManifest.xml
<activity
android:label="#string/app_name"
android:configChanges="**orientation|keyboardHidden**"
android:name=".CheckOrientationActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Corresponding Logs when i run and change the orientation
03-05 18:54:31.644: I/CheckOrientationActivity (20314): onCreate Start
03-05 18:54:35.014: I/CheckOrientationActivity (20314): onConfigurationChanged
03-05 18:54:35.014: I/ORIENTATION_LANDSCAPE(20314): ORIENTATION_LANDSCAPE
03-05 18:54:41.984: I/CheckOrientationActivity (20314): onConfigurationChanged
03-05 18:54:41.984: I/ORIENTATION_PORTRAIT(20314): ORIENTATION_PORTRAIT
There's multiple reasons why this could happen, hard to tell without seing more code.
Here's some pointers:
you haven't forced the layout to some particular orientation via manifest file or programatically (something like <activity android:screenOrientation="portrait"> in your manifest)
by default the Activity is restarted when configuration changes happend. If you want to NOT have your activity restarted when the orientation changes, you need to use
android:configChanges="orientation"
on your activity's configuration in the manifest.
the above point will in fact make Android call your activity's onConfigurationChanged(Configuration) method when the orientation changes
==update==
Also, if you have the same layout (like "main") declared in layout-land and layout-port you only need to specify that you want to use that layout in the beginning:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
and that's it. THERE IS NO NEED to also implement the
public void onConfigurationChanged(Configuration newConfig) {
//...
}
method as well. For the sake of chosing the correct layout based on orientation all you have to do is declare the same layout in those two folders.
(Also, there is NO NEED to add the android:configChanges="orientation" to your manifest, apparently it's on by default). I've tried all this just now, works ok

Categories

Resources