An Activity is being restarted just because of configuration changes like orientation, screenSize(from API level 10), keyboard hidden etc.
So what you need to do is : declare below line in your manifest file. android:configChanges="keyboard|orientation|keyboardHidden". And if you are using above version of android 2.2(API level 8) you can also declare screenSize parameter too.
Example:
Create a project and replace your code by this code
package com.retainstate;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
public class RetainActivityStateActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showDialog();
}
private void showDialog()
{
AlertDialog.Builder al=new AlertDialog.Builder(this);
al.setMessage("Hello! Activity will not restart on orientation changing.")
.setTitle("RetainStateOfActivity").setPositiveButton("OK", null).show();
}
}
Now let the main.xml as it is
In manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.retainstate"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".RetainActivityStateActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Now run the project an alertDialog will show and then change the orientation of emulator by leftCtrl+F11. you dialog will remain stay.
Source Code: download zip.file