Essential Android UI Lifecycle edit forum

Saving data on memory trimming

public class ExampleActivity extends Activity {
    private final static String EXAMPLE_ARG = "example_arg";
    private int mArg;

    protected void onCreate(Bundle savedInstanceState) {
        if(savedInstanceState != null) {
            mArg = savedInstanceState.getInt(EXAMPLE_ARG);

    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(EXAMPLE_ARG, mArg);


So, what is happening here?

The Android system will always strive to clear as much memory as it can. So, if your activity is down to the background, and another foreground activity is demanding its share, the Android system will call onTrimMemory() on your activity.

But that doesn’t mean that all your properties should vanish. What you should do is to save them into a Bundle object. Bundle object are much better handled memory wise. Inside a bundle every object is identified by unique text sequence - in the example above integer value variable mArg is hold under reference name EXAMPLE_ARG. And when the activity is recreated extract your old values from the Bundle object instead of recreating them from scratch

UI Lifecycle/
UI Lifecycle
Saving data on memory trimming

Table Of Contents
64 Menu
90 UI Lifecycle
112 Loader
119 Xposed
132 Colors
135 Fresco
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close