Search code examples
androidandroid-lifecycle

Do Activities get destroyed and recreated in Android during lifecycle events? Or do they simply get “re-attached”?


Let us consider the following example subclass of an Activity

public class CustomActivity extends Activity
{
    private int myIntVar;

    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom);

        if (myIntVar == 0)
        {
            Random rand = new Random();
            int    min  = 1;
            int    max  = 100;

            myIntVar =  rand.nextInt((max+1) - min) + min;
        }
    }

    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
    }
}

According to the official documentation for the Android lifecycle methods

The method onSaveInstanceState(...) is called to allow the application time to save its current state before being put into the background. But what happens to the object of CustomActivity that is currently loaded in memory? Does it also get created and destroyed alongside the lifecycle events? Or is it preserved perpetually in memory (as long as the application is still active - even if it's in the background) and it will simply be "re-attached" when the time comes?

In other words, throughout an Android applications entire lifespan (from the user opening it initially, to it being closed after the user swipes it away in the task-manager/menu screen) Will myIntVar only be set once, or multiple times?


Solution

  • Does it also get created and destroyed alongside the lifecycle events?

    Yes.

    Or is it preserved perpetually in memory (as long as the application is still active - even if it's in the background) and it will simply be "re-attached" when the time comes?

    No.

    Will myIntVar only be set once, or multiple times?

    For any given CustomActivity instance, once. Across all CustomActivity instances, multiple times.