Activity recycling

Handling Activity Data After Being Recycled

When an activity enters the stopped state, it may be recycled by the system.

For example, when Activity A launches Activity B, Activity A moves into the stopped state. If the system reclaims Activity A due to low memory, and the user later presses the back button to return to Activity A,

Activity A will still be displayed as usual. However, in this case, onRestart() will not be called; instead, onCreate() will be invoked because Activity A is being recreated.

If Activity A contains transient data—for instance, a text field where the user has entered some text—that data will be lost once the activity is recycled.

If this happens in our app, it will negatively impact the user experience.

Fortunately, Android provides a callback method called onSaveInstanceState(), which is guaranteed to be called before the activity is recycled.

This allows us to preserve transient data before the activity is destroyed.

The onSaveInstanceState() method receives a parameter of type Bundle.

Bundle provides a set of methods for saving data, such as putString() for strings and putInt() for integers.

Overriding the onSaveInstanceState Method

// English
@Override
protected void onSaveInstanceState(Bundle outState) { // Called before the activity is recycled
    super.onSaveInstanceState(outState);
    outState.putString("user_name", "Ms. Pan");
}Code language: JavaScript (javascript)
// English
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.e(TAG, "onCreate: ");

    if (savedInstanceState != null) // In onCreate, we can check if the Bundle contains data; if it does, the activity was recycled and is now being recreated
    {
        Log.e(TAG, savedInstanceState.getString("user_name"));
    }
}Code language: JavaScript (javascript)

Retrieving Bundle Data When the Activity Is Recreated

In the onCreate method, the system passes in a Bundle parameter:

// English
protected void onCreate(Bundle savedInstanceState) {Code language: JavaScript (javascript)

Retrieving Bundle Data

// English
if (savedInstanceState != null) // In onCreate, we can check if the Bundle contains data; if it does, the activity was recycled and is now being recreated
{
    Log.e(TAG, savedInstanceState.getString("user_name"));
}Code language: JavaScript (javascript)

Activity recycling

Leave a Reply

Your email address will not be published. Required fields are marked *