How to prevent activity restart on device orientation change only for some duration and not all the time
-
28-10-2019 - |
Question
In my activity, there is a lot of processing done in oncreate() like opening a database, writing files on the sd card. But all of this heavy processing happens only once when the activity is launched the first time and not after that. I am using an Async task to achieve this.
I am using the following code to prevent activity restart during device configuration change.
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
I wish to disable activity restart due to change in device orientation only once when the initial setup takes place and after that, I want to enable activity restart. Any idea how I can achieve this?
Solution
add this to your activity tag in manifest file
android:configChanges="orientation|keyboardHidden"
OTHER TIPS
"if you can't beat them, join them" they said. Therefore, you should better organize you application workflow.
Keep your UI-related operations in the standard lifecycle methods (onCreate, onStart, etc.) and demand the long-lasting operation to other threads.
Please take a look to AsyncTask and IntentService classes, they will be very useful to you.
To summarize, it is often easier to adapt your code to the underlying system than forcing the system itself to follow your will
The simplest way would be calling setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR)
. However I'd better consider what STT LCU is saying. Here are some articles I'd suggest start with:
http://developer.android.com/guide/topics/resources/runtime-changes.html
http://www.vogella.de/articles/AndroidPerformance/article.html#lifecycle