Android Activities And Activity Lifecycle Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    8 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of Android Activities and Activity Lifecycle

Android Activities and Activity Lifecycle

Importance of Activities in Android Development:

  • User Interaction: Activities are crucial for interacting with users as they represent different screens in the app.
  • Navigational Elements: They allow for navigation between different parts of the app.
  • Component Interaction: Activities work closely with other components such as services, broadcast receivers, and content providers to perform various tasks.

Lifecycle of an Android Activity

Understanding the lifecycle of an activity is crucial for managing its resources efficiently and providing a seamless user experience. The lifecycle of an activity consists of several states and transitions:

  1. Created State: This starts when onCreate() method is called. Here, the activity initializes itself, sets up layout using setContentView(), and binds data to lists.
  2. Started State: When onStart() is invoked, the activity becomes visible but not yet on the foreground. This typically happens just before onResume().
  3. Resumed State: The onResume() method makes the activity interact with the user. At this point, the activity is at the top of the task stack or “running”.
  4. Paused State: Occurs when another activity covers this one, but it has stayed partially visible. During this state, the app is still alive and retains its UI state, but cannot handle user input.
  5. Stopped State: The onStop() method is called when the activity is no longer visible to the user. However, the activity instance remains in memory with its last UI state preserved.
  6. Restarted State: onRestart() is called just before the activity re-starts after being stopped. It’s useful for restoring the previous state before resuming.
  7. Destroyed State: onDestroy() marks the final end of the activity's lifecycle. Generally, you release all non-memory resources here, like threads, database connections, or pending network requests.

Transition Methods in Detail:

  • onCreate(): Initializes the activity when it is created for the first time. Call super.onCreate(savedInstanceState) and set the layout using setContentView().
    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
    }
    
  • onStart(): Invoked right after onCreate() and every time an activity comes into view, except from the Resumed state.
    @Override
    protected void onStart() {
         super.onStart();
         // Start tasks that were paused or stopped during the paused or stopped states, respectively.
    }
    
  • onResume(): Called when the activity starts interacting with the user. This is the state where the most user interaction occurs.
    @Override
    protected void onResume() {
         super.onResume();
         // Register broadcast receiver, resume ongoing operations, and begin animations.
    }
    
  • onPause(): Invoked when the current activity is being paused and the user is focusing on another activity.
    @Override
    protected void onPause() {
         super.onPause();
         // Stop animations and ongoing operations, save any unsaved changes.
    }
    
  • onStop(): Called when the activity is no longer visible to the user. It is more than onPause() when activity is going to background, completely out of user view.
    @Override
    protected void onStop() {
         super.onStop();
         // Save application persistent state and stop tasks that consume CPU.
    }
    
  • onRestart(): Called after onStop() and just before onStart(). It only occurs if the activity comes back to the front from the Stopped state.
    @Override
    protected void onRestart() {
         super.onRestart();
         // Restore any member variables that were not saved in bundle.
    }
    
  • onDestroy(): Indicates that the activity has finished its execution and is about to be removed from memory.
    @Override
    protected void onDestroy() {
         super.onDestroy();
         // Clean up your code to avoid memory leaks.
    }
    
    **Saving and Restoring Instance State:**
    During configuration changes (like device rotation), Android recreates the activity. To preserve data across these transitions, use `onSaveInstanceState()` and restore it in `onCreate()` or `onRestoreInstanceState()`.
    ```java
    @Override
    protected void onSaveInstanceState(Bundle outState) {
         super.onSaveInstanceState(outState);
         // Save custom values into the bundle.
         outState.putString("key", "value");
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
         super.onRestoreInstanceState(savedInstanceState);
         // Restore values from the bundle.
         String value = savedInstanceState.getString("key");
    }
    

Key Points on Managing the Activity Lifecycle:

  • Resource Management: Properly manage resource initialization and release to prevent memory leaks.
  • Configuration Handling: Implement onSaveInstanceState() to persist data when the system destroys and re-creates the activity due to configuration changes.
  • Orientation Changes: Handle device orientation changes to ensure a smooth user experience.
  • Task Stack: Understand how activities move within the task stack and use onRestart() to refresh or update activity content.

Conclusion

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement Android Activities and Activity Lifecycle

Prerequisites:

  • Basic knowledge of Java/Kotlin.
  • Android Studio installed on your computer.
  • A basic understanding of Android development environment (AVD/Physical device).

Objective:

To create an Android application that demonstrates the lifecycle of an Activity by logging messages when different lifecycle methods are called. This will help you understand how these methods interact with each other.

Step-by-Step Guide:

1. Create a New Android Project in Android Studio

  • Open Android Studio.
  • Click on Start a new Android Studio project.
  • Choose Empty Activity.
  • Name your project ("ActivityLifecycleDemo").
  • Set the language as Java or Kotlin (we’ll use Java in this example).
  • Click "Finish".

2. Understand Activity Lifecycle

Before we start coding, let's review the lifecycle of an Android Activity:

| State | Method | Description | |----------------|------------------------------|---------------------------------------| | Created | onCreate() | Initializes the activity | | Started | onStart() | Makes the activity visible | | Resumed | onResume() | Brings the activity to the foreground | | Paused | onPause() | Pauses the activity | | Stopped | onStop() | Stops the activity | | Restarted | onRestart() | Restarts the activity | | Destroyed | onDestroy() | Finalizes the activity |

3. Modify the MainActivity to Log the Lifecycle Events

  • Open MainActivity.java.
  • Import Log class from android.util.Log.

Here’s what each method should log:

package com.example.activitylifecycledemo;

import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "LifecycleDemo";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate() has been called");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart() has been called");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume() has been called");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause() has been called");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop() has been called");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "onRestart() has been called");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy() has been called");
    }
}

4. Run Your Application

  • Connect your Android device or start an Android Virtual Device (AVD) from the AVD Manager.
  • Click on run (green triangle icon) to build and deploy your app to the device/emulator.
  • In Android Studio, open the Logcat tab (at the bottom).
  • Filter the log by your application name or tag ("LifecycleDemo") by clicking the search box and typing it there.
Expected Output:
D/LifecycleDemo: onCreate() has been called
D/LifecycleDemo: onStart() has been called
D/LifecycleDemo: onResume() has been called

5. Interact with Your Application to See How Lifecycle Methods Are Triggered

Once the app is running:

  1. Press Home Button:

    D/LifecycleDemo: onPause() has been called
    D/LifecycleDemo: onStop() has been called
    
  2. Open App Again:

    D/LifecycleDemo: onRestart() has been called
    D/LifecycleDemo: onStart() has been called
    D/LifecycleDemo: onResume() has been called
    
  3. Minimize App (using Recent Apps):

    D/LifecycleDemo: onPause() has been called
    D/LifecycleDemo: onStop() has been called
    
  4. Background Another App (Bringing back yours):

    D/LifecycleDemo: onRestart() has been called
    D/LifecycleDemo: onStart() has been called
    D/LifecycleDemo: onResume() has been called
    
  5. Rotate Your Device (will recreate activity):

    • On orientation change, onPause(), onStop(), onDestroy(), onCreate(), onStart(), onResume() are called sequentially as the activity is recreated to handle the new orientation.

6. Additional Notes

  • onSaveInstanceState(): This method can be overridden if you need to save the UI state or other information before the activity is destroyed (e.g., during configuration changes like screen rotation).

  • onRestoreInstanceState(): This method can be similarly overridden to restore the saved state during onCreate() or after onStart().

Example:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Log.d(TAG, "onSaveInstanceState(Bundle) called.");
    // Save custom data into 'outState' bundle
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    Log.d(TAG, "onRestoreInstanceState() called.");
    // Restore custom data here
}

7. Conclusion

By following these steps, you have created a simple Android application that logs all essential lifecycle events of its main activity. Observing these logs will help you understand when and how each method is called, which is crucial for effective Android app development.

You May Like This Related .NET Topic

Login to post a comment.