开发者

Android persistent state with global variables when system kills activities

开发者 https://www.devze.com 2022-12-17 08:26 出处:网络
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:

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开发者_Go百科 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消