1

In my activity I have a long process which runs in the background using a AsyncTask. A ProgressDialog is displayed while the task is being run. This works fine but if the user rotates the screen while the task is running an error occurs. I want my activity to not restart when the user rotates the screen.

I have added the below to my manifest file but each time the screen is rotated the OnCreate method is still called. (have confirmed by adding a break point in OnCreate which is hit)

android:configChanges="keyboardHidden|orientation|screenSize"

<activity android:name=".MyActivityName" android:configChanges="keyboardHidden|orientation|screenSize">       

Any suggestions?

Mark
  • 183
  • 4
  • 12

2 Answers2

1

Activities go through the life cycle on screen rotations, so it will go through onPause(). enter image description here

There are two ways to handle this.

1) add android:screenOrientation="portrait" to your manifest under that activity's <activity > tag to prevent it from changing to landscape mode.

2) try to save what your app is doing with

@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
}
DevJem
  • 656
  • 1
  • 13
  • 21
  • 1) I don't want to prevent the app from changing between portrait and landscape 2) Will adding this prevent onCreate from being fired when the screen is rotated? – Mark Mar 10 '15 at 00:38
  • Upon further reading, I've found http://android-er.blogspot.com/2013/05/how-setretaininstancetrue-affect.html – DevJem Mar 10 '15 at 00:44
  • I'm not using fragments – Mark Mar 10 '15 at 00:49
  • Ok, try http://stackoverflow.com/questions/13797934/how-to-save-asynctask-class-object-in-onsaveinstancestate – DevJem Mar 10 '15 at 00:49
  • Strange thing is I've started a new project and the same thing happens?? It's got me stumped. – Mark Mar 10 '15 at 03:05
  • @Mark if you don't want to prevent the app from changing between portrait and landscape and the onCreate method must be called, as in android when you change orientation the layout according to it must be set so that onCreate method must be called. It will be better you first post your whole requirement/problem with complete detail. – Dhrumil Shah - dhuma1981 Mar 10 '15 at 04:57
0

Don't ask me how but I had 2 entries in my manifest file for my activity. Once I removed 1 of the entries onConfigurationChanged was fired when the screen was rotated instead of onCreate.

Mark
  • 183
  • 4
  • 12