Question

I'm a little confused about the Activity being destroyed and recreated when the user's device is rotated.

I've been reading around, and I understand the rationale for doing so (it basically 'forces' the developer to make sure they haven't 'missed' anything upon rotation/language/other changes)

I'm happy to respect best practice if it is seen as such, however it begs the question:

How do I 'remember' the state of the game/app, so that when the screen is rotated I have something from which to re-generate what the user was looking at?

From what I can see, absolutely everything is destroyed, the base class constructor runs and all variables in the Activity are 'null'.

I suspect the 'savedInstanceState' (Bundle class) is where I would collect that data, but reading around it only seems to be used for when the app is closed from lack of resources (and a few other extremely fringe cases)

Am I misinformed or misunderstanding the purpose of savedInstanceState? Is it wise to abandon best practice (letting the Activity be destroyed) if I'm mindful enough to not miss anything upon rotation? Thanks in advance for any advice.

I should note this question applies to game programming (I'm not using a layout XML)

Était-ce utile?

La solution

Do you need your activity to be recreated? Is there work you want to do on rotation? savedInstanceState is where you would store data to be passed to the recreation of the Activity, but since you aren't using XML layouts you may consider just adding android:configChanges="orientation" to your activity in the manifest. This will give you manual control over what happens during rotation change.

In additional to my original comment, I would override config changes for keyboard being show as well:

android:configChanges="orientation|keyboardHidden"

If there is work you want to do on rotation change you can override onConfigChange and do anything you need there.

It's hard to say that there is a time when you should always override config changes, but I often do it when I have no dependency on resource folders that are size or orientation specific and I'm doing a lot of work that would take too much time to recreate.

Autres conseils

There are other best practices to store data while activitiy config changes.

1. Developer Doc Handling Runtime Changes
2. Alex Lockwood : Handling Configuration Changes with Fragments, This will answer all your questions reagarding config change and storing data.

Impt: Fragment file to store data. You must set setRetainInstace(true) in order to store data and retrieve while your activity config changes.

@Override 
   public void onCreate(Bundle savedInstanceState) {  
          super.onCreate(savedInstanceState);        
          // retain this fragment
          setRetainInstance(true);    
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top