Saving data on memory trimming
suggest changepublic class ExampleActivity extends Activity {
private final static String EXAMPLE_ARG = "example_arg";
private int mArg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
if(savedInstanceState != null) {
mArg = savedInstanceState.getInt(EXAMPLE_ARG);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(EXAMPLE_ARG, mArg);
}
}
Explanation
So, what is happening here?
The Android system will always strive to clear as much memory as it can. If your activity is in the background and another foreground activity needs memory, the system can call onTrimMemory() on your activity. That callback does not take a Bundle and does not by itself recreate the activity.
The sample instead uses onSaveInstanceState. The system calls it when the activity may be destroyed, and passes the same Bundle back if the activity is recreated. Inside a bundle every value is identified by a unique text key. In the example above, the integer mArg is held under the name EXAMPLE_ARG. When the activity is recreated, read the old values from the Bundle instead of recreating them from scratch.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents