Wednesday, May 11, 2011

Prevent activity restart when screen orientation has changed

By default, when the screen orientation has changed at runtime (the user has rotated the device), the activity is shut down and restarted; onDestroy() and onCreate() will be called.

To prevent the activity from being restarted, you can declare a android:configChanges in AndroidManifest.xml File, with "orientation" attribute. onConfigurationChanged() method of your activity will be called, if exist.

example:

onConfigurationChanged()

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exercise.AndroidStopOrientationChange"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidStopOrientationChange"
android:label="@string/app_name"
android:configChanges="orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>
</manifest>


package com.exercise.AndroidStopOrientationChange;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.Toast;

public class AndroidStopOrientationChange extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Toast.makeText(AndroidStopOrientationChange.this,
"onCreate()",
Toast.LENGTH_SHORT).show();
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(AndroidStopOrientationChange.this,
"onDestroy()",
Toast.LENGTH_SHORT).show();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
Toast.makeText(AndroidStopOrientationChange.this,
"onConfigurationChanged(): " + newConfig.toString(),
Toast.LENGTH_SHORT).show();
}


}


Other attributes include :
"mcc", "mnc", "locale", "touchscreen", "keyboard", "keyboardHidden", "navigation", "orientation", "screenLayout", "fontScale", "uiMode".

Details refer: http://developer.android.com/guide/topics/manifest/activity-element.html#config

No comments: