views:

705

answers:

1

In order to persist state in my android app, so that the user will return to the activity they left off at, i've set the very useful flag alwaysRetainTaskState in my manifest:

<activity android:name=".Main"
              android:label="@string/app_name"
              android:alwaysRetainTaskState="true"> 
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

This gets the job done, or so I thought; I discovered that the system can still destroy my app's activities to preserve memory, while still keeping state. To verify this, I wrote a little test app that creates a whole bunch of activities in a loop to see if my app's activities would be destroyed. Sure enough, the system destroys my activities.

With some reading, I found that I need to use onSaveInstanceState() and onRestoreInstanceState() to help maintain activity state.

To get to my question, let's say I have an Activity with a number of global variables, some of them are static and some aren't. They consist of booleans, arraylists, strings, etc. My issue is that I am confused which of these variables are persistent when an activity is destroyed. Which ones should I package into the bundle in onSaveInstanceState()? Does the system do anything to these variables when an activity is destroyed?

+2  A: 

let's say I have an Activity with a number of global variables, some of them are static and some aren't.

There is no such thing as a "global variable" in Java. Also non-final (i.e., mutable) static data members should be avoided wherever possible.

Which ones should I package into the bundle in onSaveInstanceState()?

That is impossible to answer in the abstract.

Does the system do anything to these variables when an activity is destroyed?

Possibly. Static data members live as long as the process lives. When your last activity is destroyed, your process will be terminated in the not-too-distant future, and those static data members will be eliminated. On the next run of your application, those static data members will be re-initialized.

CommonsWare
yeah I wasn't clear about what I wanted to package into the bundle. what I meant to say is: do static variables need to be saved? do the non-static? from what you say, static members won't need to be saved when saveInstanceState() is called. do the non-static variables persist when an activity is destroyed?
Sorry to resurrect--- I am also trying to determine what is the best way to ensure some user actions taken in my app that add dynamic views to the main view (actual appWidgets) will be remembered no matter what. I am not clear if it as simple as saved instance state or if I need some other kind of magic that retains their choices and rebuilds them in some way