How to deal with orientation change with a Progres

2019-01-18 03:06发布

问题:

I am showing a ProgressDialog in the onPreExecute method of an AsyncTask object and canceling the ProgressDialog in the onPostExecute method. In the doInBackground method I am making an HTTP request for user registration. I wish to allow screen orientation changes. When I change the orientation while the doInBackground method is still running, i get all sorts of fun errors like 'IllegalArgumentException: View not attached to window manager' and 'RegisterScreen has leaked window...'

How can I properly continue to show the ProgressDialog after an orientation change? Or maybe, how can I disable orientation change after the user requests to submit their registration?

回答1:

Try adding this attribute android:configChanges="orientation" to your Activity element in the AndroidManifest.xml file.



回答2:

You could try disabling orientation changes during the time you show the ProgressDialog.

at the beginning do:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

and enable back after completion:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

Hope this helps.

(If anyone has a proper solution, I would also be interested :-)



回答3:

You want to properly handle the activity lifecycle, which means saving and restoring the state of your activity, not attempting to prevent lifecycle changes. Do some reading on AsyncTask vs. the activity lifecycle.

For example: pause-and-resume-asynctasks-android and what-to-do-with-asynctask-in-onpause.



回答4:

Add this in activity tag in application manifest.xml

<activity android:label="@string/app_name" android:configChanges="keyboardHidden|orientation|screenSize" android:name=".your.package"/>



回答5:

In my case I have used

android:configChanges="orientation" 

but it did not work for me

Following is working fine

<activity android:name=".MyActivity" 
          android:configChanges="orientation|screenSize|screenLayout">
</activity>


回答6:

You can use the following code in Your Manifest

<activity android:label="@string/app_name" 
        android:configChanges="orientation|keyboardHidden" 
        android:name=".your.package">