An image is worth a 1000 words.

workflow graph of android's activity lifecycle

Source

That image generally sums up the main beats of the Android Activity lifecycle. Knowing the lifecycle allows you to think about what your application should do as it goes through this lifecycle. What information you need to save to ensure the user has a consistent experience?

I’d really like to see how Twitter handles the lifecycle on it’s timeline activity. I admire how well, even when the app crashes, it’s able to maintain the exact position I was in on my twitter feed. Try it now! Open twitter, scroll midway through your feed, then close the app. Open it back up and you’ll be in the exact same position you were just in.

If you have basic data types that you want to persist whenever the activity view has to be recreated (orientation change, background then back to foreground), then using onSaveInstanceState(Bundle) is an easy way to save your basic data types. Bundle is basically just a key-value store.

To use onSaveInstanceState, you specify a custom key in your Activity class:

public class MainActivity extends Activity {
    private static final String CUSTOM_SAVED_INSTANCE_KEY = "keyString";
    ...
}

And then override onSaveInstanceState. Make sure you call it’s super as well. If you dig into the class you’ll find that it’s saving a bunch of other information as well. Once the super has been called, save your data into the Bundle, pairing it with your key.

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    // could save something else like text from a textview
    String textToSave = "Text that you want to save";
    // save the text to the Bundle and pair it with your key
    outState.putString(CUSTOM_SAVED_INSTANCE_KEY, textToSave);
}

Now that your data has been saved, you need to retrieve it once your activity comes back to life! You can get your data back in the onCreate method. You’ll want to do a null check on the bundle to ensure data has actually been passed to your activity. If a bundle has been passed, you’ll then want to check that your key exists, that’ll really let you know that data you previously saved needs to be restored to bring the user back to their previous state. The example below sets the text of a text view to the saved data from the bundle.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(CUSTOM_SAVED_INSTANCE_KEY))
            someTextView.setText(savedInstanceState.getString(CUSTOM_SAVED_INSTANCE_KEY));
    }
}

And that’s basic activity lifecycle management for you!