articles

Home / DeveloperSection / Articles / Activity Lifecycle: Stopping and Restarting an Activity in Android

Activity Lifecycle: Stopping and Restarting an Activity in Android

Anonymous User5840 13-Nov-2014

In my previously post we cover:

This post is the further extension of these.Here we cover how to stop and re-start an Activity

Properly stopping and Restarting our activity is an important process in the activity lifecycle that ensures our user perceive that our app is always alive and doesn’t lose their progress.  There are certain scenarios in which our apps activity is stopped and restarted.

1.       The user opens the Recent Apps window and switches from our app to another app. This stops the activity in our app. If the user returns to our app from the Home screen launcher icon or the Recent Apps window, the activity restarts

2.       The user performs an action in our app that starts a new activity. The current activity is stopped when the second activity is created. I f the user press the Back button, the first activity is restarted.

3.       The user receives a phone call while using our app on his or her phone

The activity class provides two lifecycle methods, onStop()  and onRestart(), which allow us to specifically handle how our activity handles being stopped or Restarted. Unlike the paused state, which identifies a partial UI obstruction, the stopped state guarantees that the UI is no longer visible and the user’s focus is on another activity (or an entirely separate app)

 Activity Lifecycle: Stopping and Restarting an Activity in Android

When the user leaves our activity, the system calls onStop() to stop then activity(1). If the user return’s while the activity is stopped, the system calls onRestart()(2), quickly followed by onStart() (3)and onResume() (4). Notice that no matter what scenario causes the activity to stop, the system always calls onPause() before calling onStop().  

Stop an Activity

When our activity receives a call to the onStop() method , it’s no longer visible and should release  all resources that are not needed  while the user is not using it. Once the activity is stopped the system might simply kill app process without calling the activity final onDestroy() callback, so it’s important to use onStop() to release resources that might cause memory leaks.

Although the onPause() method is called before onStop(), we should use onStop() to perform larger, more CPU intensive shut-down operations , such as writing information to database.

For example, here an onStop() method that saves the contents of a draft note to persistent storage :

@Override
protected void onStop() {
       super.onStop(); // Call the super class method 
       //Save the note’s current draft , because the activity is stopping
         //and we want to be sure the current note progress isn’t lost.
        ContentValues values = new ContentValues();
        values.put(NotePad.Notes.COLUMN_NAME_NOTE, getCurrentNoteText());
        values.put(NotePad.Notes.COLUMN_NAME_TITLE, getCurrentNoteTitle()); 
          getContentResolver().update(
                        mUri , // The URI for the note to update.
                        values, // The map of column names and new values to apply to them.                          null, //no SELECT criteria are used                          null, // no WHERE criteria are used
            );
}

 1.       When the activity is stopped, the activity object is kept resident in memory and is recalled when the activity resumes and we don’t need to re-initialize the components that were created during any of the callback methods leading up to resumed state

2.       The system also keeps track of the current sate for each View in the layout, so if the user entered text into an EditText widget, that content is retained so we don’t need to save and restore it 

Start /Restart an Activity


When an activity come back to the foreground from the stopped state, it receives a call to onRestart(). The system also calls the onStart() method, which happens every time an activity becomes visible(whether being restarted or created for the first time) . The onRestart() method is called only when the activity resumes from stopped state, so we can use to perform special restorations that might be necessary only if the activity was previously stopped, but not destroyed

It’s not very often that an app needs to use onRestart() to restore the activity’s state. However, because onStop() method should essentially clean up activity’s resources , we need to re-instantiate them when the activity restarts. Yet we need to instantiate them when an activity is created for the first time (when there is no existing instance of an activity). For this reason we usually use the onStart() callback method as the counterpart on the onStop() method, because the system calls onStart() both when it creates an activity and when it restarts the activity from stopped state

Because the user might have been away from an app for a long time before coming back it, the onStart() method is a good place to verify that required system features are enabled

@Overrride
protected void onStart() {
         super.onStart(); // Call the super class method first   
      //The activity is either being restarted or started for the first time
       // so this is where we should make sure the GPS is enabled
       LocationManger locationManger = (LocationManger) getSystemService(Context.Location_service);        Boolean gpsEnabled = locationManger.isProviderEnabled (LocationManager. GPS_PROVIDER);        If(!gpsEnabled) {
        // Create a dialog here that request the user to enable GPS, and use an intent with           //the android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS action to take user to the            //Settings screen to enable GPS when they click “OK”       }
}  
@Override
protected void onRestart() {
       super.onRestart(); //Call the super class method  
                    // Activity being started from the stopped State
}
  

When the system , destroys an activity, it calls onDestroy() method for an activity. Because we should generally have released most of our resources with onStop(), by the time we receives a call to onDestroy() , there’s not much that most apps need to do. This method is our last chance to clean out resources that could lead to memory leak.

This post is referred from Google docs Stopping and Restarting an Activity

After this post, we will discuss how to re-create an action,  the final section of activity Life-cycle in Activity LifeCycle in Android: Recreating an Activity


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

Leave Comment

Comments

Liked By