articles

Home / DeveloperSection / Articles / Activity LifeCycle in Android: Recreating an Activity

Activity LifeCycle in Android: Recreating an Activity

Anonymous User6487 13-Nov-2014

Previously in Activity Life Cycle ,we cover:

This post is the further extension of these.Here we cover the final sectionabout - how to re-create an Activity

There are a few scenarios in which an activity is destroyed due to normal app behavior, such as when the user presses the Back button or your activity signals its own destruction by calling finish(). The system may also destroy your activity if it's currently stopped and hasn't been used in a long time or the foreground activity requires more resources so the system must shut down background processes to recover memory.

  • When an activity is destroyed because the user presses Back or the activity finishes itself, the system's concept of that Activity instance is gone forever because the behavior indicates the activity is no longer needed.
  • However, if the system destroys the activity due to system constraints (rather than normal app behavior), then although the actual Activity instance is gone, the system remembers that it existed such that if the user navigates back to it, the system creates a new instance of the activity using a set of saved data that describes the state of the activity when it was destroyed. The saved data that the system uses to restore the previous state is called the "instance state" and is a collection of key-value pairs stored in a Bundle object.

NOTE:   Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout)

By default, the system uses the Bundle instance state to save information about each View object in your activity layout (such as the text value entered into an EditText object). So, if your activity instance is destroyed and recreated, the state of the layout is restored to its previous state with no code required by you. However, your activity might have more state information that you'd like to restore, such as member variables that track the user's progress in the activity.

In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android: id attribute.

To save additional data about the activity state, you must override the onSaveInstanceState() callback method. The system calls this method when the user is leaving your activity and passes it the Bundle object that will be saved in the event that your activity is destroyed unexpectedly. If the system must recreate the activity instance later, it passes the same Bundle object to both the onRestoreInstanceState() and onCreate() methods.

Activity LifeCycle in Android: Recreating an Activity 

Save Your Activity State

As an activity begins to stop, the system calls onSaveInstanceState() so an activity can save state information with a collection of key-value pairs. The default implementation of this method saves information about the state of activity view hierarchy, such as the text in the EditText widget or the scroll position of a Listview

To save activity state information we must need to implement onSaveInstanceState() and add key-value pairs to the Bundle object. For example :

Static final String STATE_SCORE = “playerScore”;
Static final String STATE_LEVEL = “playerLevel”;
…….
@Override
 public void onSaveInstanceState(Bundle savedInstanceState) {
           // Save the user’s current game state
               savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
               savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
             // Always call the superclass so it can save the view hierarchy state
                 Super.onSaveInstanceState(savedInstanceState);
}

 Restore Activity State

Once activity is recreated after it was previously destroyed, we can recover our state from the Bundle that the system passes our activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle  that contains the instance state information

Because the onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.

Here’s how we can restore data in onCreate() :

@Override
protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedinstanceState); // Call the superclass
     // check weather we are recreating a previously destroyed instance
        if(savedInstanceState ! = null) {
           //Restore value of members from the saved state
                   mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
                  mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
        } else {
                // Initialize members with default values for a new instance
        }
}

 

Instead of restoring the state during onCreate() we may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so we  do not need to check whether the Bundle is null:

public void onResoreInstanceState(Bundle savedInstanceState) { 
       // Call the superclass so it can restore the view hierarchy
           super.onRestoreInstanceState(savedInstanceState);
       //Restore state members from saved Instance
          mCurrentScore = savedInstanceState.getInt(STATE_SCORE) ;
          mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}
 

 This post is referred from Google docs Recreating an Activity

Next, we are going to learn  a new component called "Fragments" in Building a Dynamic UI with Fragments


Updated 07-Sep-2019
I am a content writter !

Leave Comment

Comments

Liked By