In your manifest, in an activity/fragment activity tag, please add the following,
android:configChanges="orientation"
Above line will notify your activity/fragmentactivity when there is an orientation change. In order for you to do something on it, you need to override the following method in your activity,
public void onConfigurationChanged(Configuration newConfig) {
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
Log.e("On Config Change","LANDSCAPE");
}else{
Log.e("On Config Change","PORTRAIT");
}
}
Hope this helps
EDIT:
Please see the complete code below,
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.example.android.customviews.R;
public class TestActivity extends FragmentActivity {
Dialog mDialog = null;
@Override
protected void onCreate(Bundle pSavedInstanceState) {
super.onCreate(pSavedInstanceState);
setContentView(R.layout.activity_calendar);
((Button) findViewById(R.id.openButton)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View pV) {
mDialog = ProgressDialog.show(TestActivity.this, "", "Please Wait...");
new WasteTime().execute(null, null, null);
}
});
}
@Override
public void onConfigurationChanged(Configuration pNewConfig) {
super.onConfigurationChanged(pNewConfig);
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
if (pNewConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setContentView(R.layout.activity_camera);
Log.e("On Config Change", "LANDSCAPE");
}
}
class WasteTime extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... pParams) {
final int timeWaster = 10000;
for (int i = 0; i < timeWaster; i++) {
Log.e("Wasting Time", i + "milliseconds wasted");
}
return null;
}
}
}
Manifest:
<activity
android:name="com.example.android.activities.TestActivity"
android:theme="@style/ApplicationTheme_ActionBar"
android:configChanges="orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
This is what I did. I just forgot to dismiss a dialog properly. But rest is working. However if you are using a fragment then that might not work for you as it is for an activity or a Fragment Activity.