For the More Curious: Current State of Activity Cleanup

As of this writing, activities themselves are not individually destroyed in low-memory situations. Instead, Android clears an entire app process from memory, taking any of the app’s in-memory activities with it. (Each application gets its own process. You will learn more about Android application processes in the section called For the More Curious: Processes vs Tasks in Chapter 24.)

Processes containing foreground (resumed) and/or visible (paused) activities get higher priority than other processes. When the OS needs to free up resources, it will select the lower priority processes first. Practically speaking, a process containing a visible activity will not reclaimed by the OS. If a foreground process does get reclaimed, that means something is horribly wrong with the device (and your app being killed is probably the least of the user’s concerns).

If you are overriding onSaveInstanceState(Bundle), you should test that your state is being saved and restored as expected. Rotation is easy to test. And, luckily, so is the low-memory situation. Try it out now to see for yourself.

Find and click on the Settings icon within the list of applications on the device. When the Settings screen appears, click Developer options (you will need to scroll down until you see the option you are looking for). On the Developer options screen you will see many possible settings. Turn on the setting labeled Don’t keep activities, as shown in Figure 3.15.

Figure 3.15  Don’t keep activities

Screenshot shows Developer options screen on an Android phone.

Now run your app and press the Home button. Pressing Home causes the activity to be paused and stopped. Then the stopped activity will be destroyed, just as if the Android OS had reclaimed it for its memory. Restore the app to see if your state was saved as you expected. Be sure to turn this setting off when you are done testing, as it will cause a performance decrease and some apps will perform poorly.

Remember that pressing the Back button instead of the Home button will always destroy the activity, regardless of whether you have this development setting on. Pressing the Back button tells the OS that the user is done with the activity.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.40.177