Android Activity Lifecycle

In android, Activity represents a single screen with a user interface (UI) of an application and it will act as an entry point for users to interact with an app.

Generally, the android apps will contain multiple screens and each screen of our application will be an extension of the Activity class. By using activities, we can place all our android application UI components on a single screen.

From the multiple activities in the android app, one activity can be marked as a main activity and that is the first screen to appear when we launch the application. In the android app, each activity can start another activity to perform different actions based on our requirements.

For example, a contacts app which is having multiple activities, in that the main activity screen will show a list of contacts and from the main activity screen we can launch other activities that provide screens to perform tasks like adding a new contact and searching for the contacts. All these activities in the contact app are loosely bound to other activities but will work together to provide a better user experience.

Generally, in android, there is a minimal dependency between the activities in an app. To use activities in an application we need to register those activities' information in our app’s manifest file (AndroidMainfest.xml) and need to manage the activity life cycle properly.

<?xml version="1.0" encoding="utf-8"?>
<manifest..>
    <application..>
        <activity android:name=".MainActivity" >
          …….    

          …….

        </activity>

     …….

</application>
</manifest>

The activity attribute android: name will represent the name of the class and we can also add multiple attributes like icon, label, theme, permissions, etc. to an activity element based on our requirements.

public class MainActivity extends Activity {
           .......
}

Android Activity Lifecycle

Generally, the activities in our android application will go through different stages in their life cycle. In android, the Activity class has 7 callback methods like onCreate(), onStart(), onPause(), restart(), onResume(), onStop() and onDestroy() to describe how the activity will behave at different stages.

By using activity cal-back methods we can define how our activity can behave when the user enters or leaves our application.

Android Activity Lifecycle Callback Methods

In Android, an activity goes through a series of states during its lifetime. By using callback methods we can get the activity transitions between the states.

Android system initiates its program within an Activity starting with a call on onCreate() callback method. There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity.

This section will give you detailed information about callback methods to handle activity transitions between states during the lifecycle.

onCreate()

This is the first callback method and it fires when the system creates an activity for the first time. During the activity creation, the activity entered into a Created state.

If we have an application start-up logic that needs to perform only once during the life cycle of an activity, then we can write that logic in onCreate() method.

Following is an example of defining a onCreate() a method in android activity.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

Once onCreate() method execution is finished, the activity will enter into Started state and the system calls the onStart() method.

onStart()

The onStart() callback method will invoke when an activity is entered into Started State by completing onCreate() method. The onStart() the method will make an activity visible to the user and this method execution will finish very quickly.

Following is an example of defining a onStart() the method in android activity.

@Override
protected void onStart()
{
    super.onStart()
}

After completion of onStart() method execution, the activity enters into a Resumed state and the system invokes the onResume() method.

onResume()

When an activity entered into the Resumed state, the system invokes onResume() the call-back method. In this state, activity starts interacting with the user which means the user can see the functionality and design part of an application on a single screen.

Mostly the core functionality of an app is implemented in onResume() method.

The app will stay in this Resumed state until another activity happens to take focus away from the app like getting a phone call or the screen turned off, etc.

In case any interruption events happen in the Resumed state, the activity will enter into Paused state and the system will invoke onPause() method.

After an activity returned from Paused state to a Resumed state, the system again will call onResume() method due to this we need to implement onResume() method to initialize the components that we release during onPause() method

Following is an example of defining a onResume() the method in android activity.

@Override
public void onResume() {
    super.onResume(); 
    if (mCamera == null) {
        initializeCamera();
    }
}

If any interruption happens in the Resumed state, the activity will enter into Paused state and the system will invoke onPause() the method.

onPause()

Whenever the user leaves an activity or the current activity is Paused then the system invokes onPause() the method. The onPause() the method is used to pause operations like stopping playing the music when the activity is in a paused state or passing an activity while switching from one app to another app because every time only one app can be focused.

Following is an example of defining a onPause() the method in android activity.

@Override
public void onPause() {
    super.onPause();
  if (mCamera != null) {
        mCamera.release();
        mCamera = null;
    }
}

After completion of onPause() method execution, the next method is either onStop() or onResume() depending on what happens after an activity entered into a Paused state.

onStop()

The system will invoke onStop() callback method when an activity is no longer visible to the user, the activity will enter into the Stopped state. This happens due to current activity entered into a Resumed state or newly launched activity covering the complete screen or it’s been destroyed.

The onStop() the method is useful to release all the app resources which are no longer needed by the user.

Following is an example of defining a onStop() method in android activity.

@Override
protected void onStop()
{
    super.onStop();
}

The next callback method raised by the system is either, onRestart() in case the activity comes back to interact with the user or onDestroy() in case the activity finished running.

onRestart()

The system will invoke onRestart() method when an activity restarts itself after stopping it. The onRestart() method will restore the state of activity from the time that is being stopped.

The onRestart() callback method in android activity will always be followed by onStart() the method.

onDestroy()

The system will invoke onDestroy() the method before an activity is destroyed and this is the final callback method received by the android activity.

The system will invoke this onDestory() callback method either the activity is finished or the system destroys the activity to save space.

Following is an example of defining a onDestroy() the method in android activity.

@Override
public void onDestroy()
{
    super.onDestroy();
}

The onDestroy() the method will release all the resources which are not released by the previous callback onStop() method.

Android Activity Lifecycle Diagram

Generally, in android activity class uses different callback methods like onCreate(), onStart(), onPause(), onRestart(), onResume(), onStop() and onDestroy() to go through different stages of the activity life cycle.

Following is the pictorial representation of the Android Activity Life cycle which shows how Activity will behave in different stages using callback methods.

Whenever the user trying to leave an activity like switching from one app to another app, the system will use callback methods to dismantle the activity completely or partially to resume the activity from where the user left off.

Based on our requirements we can implement the activity in the android app using the callback method and it’s not necessary to use all callback methods in each android application.

Android Activity Lifecycle Example

Now we will see, how the android activity lifecycle will work with an example. Following is the example of invoking activity callback methods to see the life cycle process of activity in an android application.

MainActivity.java File Code

The following are the code modifications made to include all life cycle callback methods in the MainActivity.java file.

If you observe the above code we defined a statement like “setContentView(R.layout.activity_main);” which will help to load all UI components defined in the activity_main.xml file and use Log.d() method to generate log messages.

package com.example.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("Activity Lifecycle","onCreate invoked");
    }
    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Activity Lifecycle","onStart invoked");
    }
    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Activity Lifecycle","onResume invoked");
    }
    @Override
    protected void onPause() {
        super.onPause();
        Log.d("Activity Lifecycle","onPause invoked");
    }
    @Override
    protected void onStop() {
        super.onStop();
        Log.d("Activity Lifecycle","onStop invoked");
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("Activity Lifecycle","onRestart invoked");
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("Activity Lifecycle","onDestroy invoked");
    }
}

In our application, we can have more than one activity file and we need to declare all the activities in the AndroidManifest.xml file. In the manifest XML file, by using MAIN action and LAUNCHER category attributes in intent filters (<intent-filter>) we can mention the main activity that opens when the user initially launches our app with the launcher icon. In case we didn’t mention the MAIN action, then the system will decide which activity needs to start and if we didn’t add the LAUNCHER category for the main activity, our app icon will not appear in the home screen’s list of apps.

The code of the AndroidManifest.xml file will be as shown below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutlane.helloworld" >
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
          <intent-filter>
              <action android:name="android.intent.action.MAIN" />
             <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
       </activity>
    </application>
</manifest>

The output of Android Activity Lifecycle Example

Now run your application using Android Virtual Device (AVD) in android studio by clicking on the Play icon in the toolbar or pressing Shift + F10. Our application result will be as shown below.

Now open Android Device Monitor to see our log messages in the LogCat window in android studio as shown below.

If you observe log messages in LogCat window onCreate, onStart, and onResume methods are invoked by the system.

Now click on the Home button in Android Emulator, and immediately activity is entered into Paused state and the system will invoke onPause() the method as shown below.

After a while, the activity will enter into the Stopped state and the system will invoke onStop() a method as shown below.

Now again launch our app from the Home screen list of apps as shown below.

If you observe log messages in the LogCat window again on the restart, onStart, and onResume methods are invoked by a system as shown below.

Now click on the Back button in the android emulator, and the system will invoke the onPause method after a while onStop, and onDestroy methods will be invoked as shown below

Here we need to remember that the onCreate and onDestroy methods will invoke only once throughout the activity life cycle.

This is how the android activity life cycle process will invoke different methods while transitioning from one stage to another stage.

Did you find this article valuable?

Support Hemant Maurya by becoming a sponsor. Any amount is appreciated!