Why not use always android:configChanges="keyboardHidden|orientation"? - android

I was wondering why not use android:configChanges="keyboardHidden|orientation" in every (almost every ;)) activity?
Goods:
no need to worry about your activity been rotated
it's faster
Not so nice:
need to change your layouts if they are depending on screen size (e.g. layouts with two columns or so)
Bad:
no flexible way to have different layouts on different orientation
not so good when using fragments
But if we don't use different layouts, why not?

Quick Background
By default, when certain key configuration changes happen on Android (a common example is an orientation change), Android fully restarts the running Activity to help it adjust to such changes.
When you define android:configChanges="keyboardHidden|orientation" in your AndroidManifest, you are telling Android: "Please don't do the default reset when the keyboard is pulled out, or the phone is rotated; I want to handle this myself. Yes, I know what I'm doing"
Is this a good thing? We shall soon see...
No worries?
One of the pros you start with is that there is:
no need to worry about your activity been rotated
In many cases, people mistakenly believe that when they have an error that is being generated by an orientation change ("rotation"), they can simply fix it by putting in android:configChanges="keyboardHidden|orientation".
However, android:configChanges="keyboardHidden|orientation" is nothing more than a bandaid. In truth, there are many ways a configuration change can be triggered. For example, if the user selects a new language (i.e. the locale has changed), your activity will be restarted in the same way it does by an orientation change. If you want you can view a list of all the different types of config changes.
Edit: More importantly, though, as hackbod points out in the comments, your activity will also be restarted when your app is in the background and Android decides to free up some memory by killing it. When the user comes back to your app, Android will attempt to restart the activity in the same way it does if there was some other configuration change. If you can't handle that - the user will not be happy...
In other words, using android:configChanges="keyboardHidden|orientation" is not a solution for your "worries." The right way is to code your activities so that they are happy with any restart Android throws at them. This is a good practice that will help you down the road, so get used to it.
So when should I use it?
As you mentioned there is a distinct advantage. Overwriting the default configuration change for a rotation by handling it yourself will speed things up. However, this speed does come with a price of convenience.
To put it simply, if you use the same layout for both portrait and landscape you're in good shape by doing the overwrite. Instead of a full-blown reload of the activity, the views will simply shift around to fill the remaining space.
However, if for some reason you use a different layout when the device is in landscape, the fact that Android reloads your Activity is good because it will then load up the correct layout. [If you use the override on such an Activity, and want to do some magical re-layout at runtime... well, good luck - it's far from simple]
Quick Summary
By all means, if android:configChanges="keyboardHidden|orientation" is right for you, then use it. But PLEASE be sure to test what happens when something changes, because an orientation change is not the only way a full Activity restart can be triggered.

From my point of view: If the layout is the same in both landscape and portrait mode - you might aswell disable one of the two in your app.
The reason why I state this is that I as a user expect the app to provide me with some benefit, when I change orientation. If it doesn't matter how I hold my phone, then I don't need the choice.
Take for instance an app where you have a ListView, and upon clicking a ListItem you want to be shown a detailed view for that item. In landscape you would od this by dividing the screen in two, having the ListView on the left and the detailed view on the right. In Portrait you would have the list in one screen and then change the screen to the detailed view when a ListItem is selected. In that case orientation change makes sense as well as different layouts.

I don see why.... occasional restarts are ok in my opinion... configChanges handles most cases for me... well maybe in some types of applications this can be problem but it depends really on type of app and how you restore state when app restarts... When one of my app restarts user is logged back and last activity opens by my code and user jus loses some steps to go back where he was but not big deal.. In other some state is always persisted and some state is always restored on restart. When activity restarted it had to be that app have not been used or something... so no problem at all... In game for example this can be problem maybe or in some other type of app I don't know...
I say that when you do it this way applications just works fine under normal circumstances. And code is much more readable without ton of logic needed for saving and restoring where u just can make new bugs and have to maintain it all the time... sure if android gets out of power and kill you application window it lose the context and starts again, but this happen just in special situations and on newer devices I belive this is more and more rare...
So kill me, but I use this across applications quite successfully...
android:configChanges="locale|keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
But I understand that for some special kind of applications it may be not good way but most of apps can live with this just OK.

Yeah I think pausing will make it quicker than releasing the player. Still have the pause though.
Have now found a solution that won't pause the song.
State in the manifest that you will handle the config change for screen orientation and then use the onConfigurationChanged method to load the layout file. By doing this in logCat I can see onPause, onCreate & onResume aren't called, and therefore the song isn't paused.
update the manifest to handle the orientation.
android:configChanges="orientation|screenSize"
add this code
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
setContentView(R.layout.activity_main);
}

Related

YouTubePlayerSupportFragment in a single-Activity app with orientation change

I tried to solve this problem, searched through the Internet, no real answer was found.
I'm developing an app where the YouTube player is needed. This player is the YouTubePlayerSupportFragment since it's in a support fragment (so it's also nested). After the initial setup I realized that whenever I rotate the phone, the video stops playing and it has to be restarted again. This is obviously not what I want.
Then I found some SO answers (like this) where people say that the Activity needs to handle the config changes, so I added android:configChanges="keyboardHidden|orientation|screenSize" to the Activity in the manifest. This solved the problem, the video now keeps playing even on orientation change and the full-screen rotation doesn't look ugly. Cool, I said, only to realize that this messed up big time the other parts of the app because the config is now being updated after all the views are in place. This means that if my phone was in portrait mode and I rotated it to landscape, the layout being used was still going to be the portrait one.
I found solutions for this suggesting calling setContentView(...) in the Activity's onConfigurationChanged(...) and reinflating the view in the Fragments, but this seems to be a rather cumbersome if not terrible solution as It's not just a simple content setting I need, the fragments need to be retained (e.g. scroll position in RecyclerView) too. The built-in setRetainInstance(true) does not work in this case as the view would be recreated with that either, but the config is still the old one when the onCreateView(...) is being called.
It would be nice if I could catch the configChanges events if the user is on that screen (fragment) only but retain Activity recreation anywhere else.
Don't suggest using more Activities, I cannot use a separate Activity for this screen and the rest of the app because of UI/UX reasons.
As per this YouTube Android Player API Guidelines
It is encouraged that you handle configuration changes caused by
orientation in your activity manually, to avoid recreating this
fragment's view every time the configuration changes. For the best
user experience, you should also manually handle the fullscreen event
by changing the layout of your activity.(See the second approch)
As you are already handling on configuration change on your own, I can see two possible solutions of your problem.
Set setFullscreenControlFlags (To your YouTubePlayer object) to FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE (This will causes the player to automatically enter fullscreen whenever the device enters landscape orientation.) in conjunction with FULLSCREEN_FLAG_CONTROL_ORIENTATION(To enable automatic control of the orientation.) flag.
Note that this flag should only be set if your activity is locked in
portrait (and is specified as such in the manifest).
The flag is useful if you don't have a landscape layout for your
activity, but would like to enable landscape orientation solely for
fullscreen video watching.
This approach might solve your problem and it is also suggested by official documentation as I mentioned above. In setFullscreenControlFlags method set FULLSCREEN_FLAG_CUSTOM_LAYOUT, that disables the default fullscreen layout handler, enabling you to control the transition to fullscreen layout manually. As well as enabling you to implement a custom fullscreen layout, this option also provides the advantage of avoiding the rebuffering that occurs in the default fullscreen behavior.
An application implementing custom fullscreen behavior should ensure
two things
That the player's view takes up the whole available space of
application's window whenever onFullscreen(boolean) is called. That
the activity is not recreated when the orientation changes to
landscape. To achieve this for an activity that supports portrait, you
need to specify that your activity handles some configuration changes
on its own in your application's manifest, including orientation,
keyboardHidden and screenSize.
See here on how to use this flag.
As per the first link I shared, this second approach will avoid recreating fragment's view every time the configuration changes. Also you don't need to call setContentView(...) in onConfigurationChanged(...).
Hope this will help you.

Stopping onCreate being executed on screen rotation in Android

I have an activity with 4 elements. A spinner containing a list of dates, a spinner containing a list of hours, a button and a list view. The spinner's selected items are used to form a web service URL which is called when the button is clicked and the response is shown in the list view.
The issue is if the user views the app in portrait mode, chooses a date, chooses an hour and clicks the button, the response of the web service call is shown in the list view however, if the device is rotated to landscape then the data in the list view is gone (because in order to get it there a button click is needed).
I understand that onCreate is called when the screen is rotated. I do not want to force the orientation so is there any way I can stop the list view being cleared? Note that the selected values in my spinners remain the same after rotation, it is just the response in the list view that is lost.
Simplest way to prevent activity recreation put this in you AndroidManifest
<activity android:name=".YourActivityName"
android:configChanges="orientation|keyboardHidden|screenSize">
Read this for more info - Supporting Multiple Screens
You can force activity screen orientation in AndroidManifest.xml by setting screenOrientation property:
<activity android:name=".FooActivity"
android:screenOrientation="portrait"/>
This is a half-solution. If you want to handle screen rotation, you should save and restore activity state. This is the major, royal PITA in any Android application I've seen.
The problem is, that your application logic is mixed with view code, which can be destroyed at any moment. Perfect combination, Google! It's like running a function that can disappear during execution. :)
To counter this sorry design decision you may want to move your application logic to service, which will not be destroyed when screen rotates. This 2-layer design is closer to universally accepted MVC pattern, as you separate your logic from your view. Service stays, activity attaches and detaches from service on demand, making screen rotation handling a breeze.
If you're dealing with webservices, do not try to invent your own solution for this. There is couple of nice libraries to handle this nicely, such as RoboSpice and you'll probably never come with any quick solution that is as good as those libs. Give it a try.
Also, watch this Google I/O video about developing Android REST client applications: https://www.youtube.com/watch?v=xHXn3Kg2IQE
Have your button set a static class variable, or shared preference. Then, call a method that reads that value, and does what you want. THEN, put a call to that same method, in onResume(), possibly based on a condition... I think that's what's worked for me. When you come back from configuration change or kill, onResume() should re-do whatever you had last done.

Android onConfigurationChanged() only in certain cases

I have stumbled on a problem, that, when the screen turns off while being in LANDSCAPE orientation, certain devices "rotate" the app back to PORTRAIT position (because the lockscreen is PORTRAIT only or something like that). I did a little research before posting this, and most popular work-around is to modify app's configuration change process to prevent activity being recreated after the configuration has changed.
But disabling activity recreation is not a solution for me, because my app supports both orientations with sepparate layout's etc.
So i would like to find out, is it possible to disable the configuration change only in special cases (Screen turned off and orientation is landscape)? Or is the right way to override onConfigurationChanged() then manually manage activity recreation inside that function (i guess simply setting different layout resources when orientation is changed simply wont cut it)?
Or is the right way to override onConfigurationChanged() then manually manage activity recreation inside that function?
Yes to an extent.
You cannot set the configChanges attribute programmatically. I guess it's to do with the way an Activity is created. They're created from the XML first and then the overridden methods in your activity implementation are invoked. There's nothing in the API that lets you change the configChanges attribute.
Now in your case it doesn't sound like you need to. If you support both orientations, then if the user locks the device and it rotates back why does it matter? From a UX perspective we know it's in portrait mode again. So should your app when it opens back up.

What is the advantage of letting an activity be destroyed on rotation?

I have used both approaches:
Let the activity be destroyed on rotation
Don't let the activity be destroyed on rotation
My approach almost everytime is to catch the rotation event and if needed call the setContentView and add some components again. If not, just let it rotate and the layouts are designed to adapt.
So far I only have seen advantages on letting it be destroyed on screens with very complex construction that are very dynamic, and whenever I rotate and not destroy show some flickering when re-building the screen.
The overhead of having to pass the state with onSaveInstance, onRestoreInstace is sometimes very error prone, and somehow time consuming.
Am I missing something?
UPDATE:
I'm not doing any kind of if "Orientation.XPTO == ..." on my code. This is the logic of each of the 2 approaches (the code is reused):
When destroying
onCreate -> DrawUI() setContentView and add views -> fill() add content
When not destroyed:
onCreate -> DrawUI() setContentView and add views -> fill() add content
onRotation -> DrawUI() setContentView and add views -> fill() add content
When calling setContentView after rotation it will pick the right layout for the device orientation (Check this answer by Google's Reto Meier https://stackoverflow.com/a/456918/327011 )
And the DrawUI and fill would have to have the logic for both the portrait and landscape layouts as the activity can be created on each of the two orientations to begin with.
Am I missing something?
Yes. You are assuming that your alternative is somehow less error prone.
By not going through the destroy-and-recreate cycle, you have to ensure that you are handling changing every resource for every possible configuration change.
Don't let the activity be destroyed on rotation
Unless you are using android:screenOrientation to force your activity into a single orientation (e.g., landscape), you cannot only handle rotation-related configuration changes. You need to handle all configuration changes. Otherwise, as soon as the user drops their device into a dock, removes it from a dock, changes language from Settings, attaches or detaches a keyboard, changes the global font scaling, etc., your app will break.
This, in turn, means that on every configuration change, you need to:
update your UI for your potentially new string resources
adjust or reload your layouts (and by "adjust" that includes changing any drawables, animations, menus, etc.)
anything else tied to your resources (e.g., array lists in your PreferenceFragment)
The problem is that you are going to forget something. For example, you will miss changing a string associated with an action bar item, so now most of your UI is in Spanish and that action bar item is in English. The sorts of things you are going to forget will be less obvious (how often do you test your Spanish translation?).
Your activity is destroyed to give you the opportunity to reconfigure yourself for the new orientation.
From the developer.android.com:
When the screen changes orientation, the system destroys and recreates
the foreground activity because the screen configuration has changed
and your activity might need to load alternative resources (such as
the layout).
For example, in landscape mode you may require a completely different layout, or may want to load in graphics that would not appear stretched. The best way of doing this is allowing the activity to be created again, which will allow the linking to the layout file to change to a more orientation-friendly layout.
See http://developer.android.com/training/basics/activity-lifecycle/recreating.html for more info and how to deal with the orientation change
If you want to disable the recreation you can add
android:configChanges="orientation"
to your Activity element in AndroidManifest.xml. This way your Activity will not be reloaded.
onSaveInstance and onRestoreInstace should only be used for passing through session information, for example the current text in a TextField, and nothing generic that can just be loaded in again after onCreate.
If you, restarting the Activity, requires recovering large sets of data, re-establishing a network connection, or perform other intensive operations then using the onSaveInstanceState() could potentially cause your noted symptoms:
A poor user experience (i.e. "show some flickering")
Require consumption of a lot of memory
onSaveInstanceState() callbacks are not designed to carry large objects.
To retain an object during a runtime configuration change:
Override the onRetainNonConfigurationInstance() method to return the object you would like to retain.
When your activity is created again, call getLastNonConfigurationInstance() to recover your object.
However:
While you can return any object, you should never pass an object that is tied to the Activity, such as a Drawable, an Adapter, a View or any other object that's associated with a Context. If you do, it will leak all the views and resources of the original activity instance. (Leaking resources means that your application maintains a hold on them and they cannot be garbage-collected, so lots of memory can be lost.)
Source
Unless you are able to pass the Object(s) smoothly I personally think it is more advantageous to handle the configuration change yourself, meaning not to destroy.
If you have a target API of 13 or higher: You must include screenSize in your configChanges. Starting with API 13 the screen size also changes on orientation change and you'll need to account for this. Prior to 13 your Activity would handle this itself.
android:configChanges="orientation|screenSize"
Some time it is useful when you are using different layouts for (Landscape / Portrait ). and using different type of views for example ListView in portrait and GridView in landscape.
I guess you are not considering the standard way of creating the android layouts. Please correct me If I'm wrong. Are you using two res folders with -port,-land separately to tell android system to choose in runtime to load the different assets and layout on the basis of orientation.
This example can give you a clue to manage layouts in different orientations.
Here is the android stanard document. Please check with "land" and "port".
Hope this will help you.

Suspend orientation change

Documentation says: "a configuration change (such as a change in screen orientation, language, input devices, etc) will cause your current activity to be destroyed, going through the normal activity lifecycle process of onPause(), onStop(), and onDestroy()."
I would like to suspend the orientation change, since it crashes my app if it was done in the middle of a a loop (of reading a file).
How can I do this? Also - looking for some kind of "onOrientationChnage" function :)
First, why not solve the initial problem instead?
90% of the times, the problem that you are facing (when changing orientation) is solved in this question:
Background task, progress dialog, orientation change - is there any 100% working solution?
Read it, correct your code and see if the problems are gone!
If you still want to do it anyway:
Quoting the documentation:
Note: Handling the configuration
change yourself can make it much more
difficult to use alternative
resources, because the system does not
automatically apply them for you. This
technique should be considered a last
resort and is not recommended for most
applications.
Still want to do it? Read the following link (where I also found the quotation):
http://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange
If you rely on android system to use different layouts when you are on portrait/landscape mode, you'll need to start to handle these differences by yourself. If you don't use these features, you may get away without doing nothing fancy :)
If you always want a particular orientation, you can add android:screenOrientation="portrait" (or ="landscape" as an attribute to your tag in the manifest.
At run time, you can call setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Categories

Resources