Android - Activity continues running while rotations are going on
-
28-10-2019 - |
Question
In my activity, I have a inner class called A
extends AsyncTask
. I don't want activity destroys and recreates again when device is rotated. I want it keep running. I have read this link RotationAsync
.They use a static class of AsyncTask. I have declared many variables in my activity, so if i use static class , I can not use variables of activity. Is there another way to do like link above without using static class of AsyncTask
? Thanks for your answers. Sorry if my english has some mistakes.
Solution
You can prevent your Activity to restart using this settings on the Manifest:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
After doing that, you can manage the changes using this code
@Override public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//do something here
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
//do something here
}
}
For more info, you can read http://developer.android.com/guide/topics/resources/runtime-changes.html
OTHER TIPS
To preserve your variables, you can save them into a Bundle and reload the state of your Activity when it is recreated. This should get you started: http://developer.android.com/guide/topics/fundamentals/activities.html#SavingActivityState