[go: up one dir, main page]

Open In App

Activity Lifecycle in Android with Demo App

Last Updated : 08 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Android, an activity is referred to as one screen in an application. It is very similar to a single window of any desktop application. An Android app consists of one or more screens or activities. 
Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when a new activity starts, the previous one always remains below it. There are four stages of an activity. 

  1. If an activity is in the foreground of the screen i.e at the top of the stack, then it is said to be active or running. This is usually the activity that the user is currently interacting with.
  2. If an activity has lost focus and a non-full-sized or transparent activity has focused on top of your activity. In such a case either another activity has a higher position in multi-window mode or the activity itself is not focusable in the current window mode. Such activity is completely alive.
  3. If an activity is completely hidden by another activity, it is stopped or hidden. It still retains all the information, and as its window is hidden thus it will often be killed by the system when memory is needed elsewhere.
  4. The system can destroy the activity from memory by either asking it to finish or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.

For each stage, android provides us with a set of 7 methods that have their own significance for each stage in the life cycle. The image shows a path of migration whenever an app switches from one state to another. For a deeper understanding and practical experience of handling lifecycle events in Kotlin, the Android Mastery with Kotlin: Beginner to Advanced course provides hands-on projects and in-depth lessons

Activity Lifecycle in Android

Detailed introduction on each of the method is stated as follows: 

1. onCreate()

It is called when the activity is first created. This is where all the static work is done like creating views, binding data to lists, etc. This method also provides a Bundle containing its previous frozen state, if there was one. 

Example: 

Java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
      
        // Bundle containing previous frozen state
        setContentView(R.layout.activity_main);
      
        // The content view pointing to the id of layout
        // in the file activity_main.xml
        Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show();
    }
}
Kotlin
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // Bundle containing previous frozen state
        setContentView(R.layout.activity_main)

        // The content view pointing to the id of layout
        // in the file activity_main.xml
        val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show()
        }
}

2. onStart() 

It is invoked when the activity is visible to the user. It is followed by onResume() if the activity is invoked from the background. It is also invoked after onCreate() when the activity is first started.  

Example:  

Java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
      
        // Bundle containing previous frozen state
        setContentView(R.layout.activity_main);
      
        // The content view pointing to the id of layout
        // in the file activity_main.xml
        Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show();
    }

    protected void onStart()
    {
        // It will show a message on the screen
        // then onStart is invoked
        Toast toast = Toast.makeText(getApplicationContext(), "onStart Called", Toast.LENGTH_LONG).show();
    }
}
Kotlin
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show()
        }

    override fun onStart() {
        super.onStart()
        // It will show a message on the screen
        // then onStart is invoked
        val toast  = Toast.makeText(applicationContext, "onStart Called", Toast.LENGTH_LONG).show()
    }
}

3. onRestart() 

It is invoked after the activity has been stopped and prior to its starting stage and thus is always followed by onStart() when any activity is revived from background to on-screen.  

Example:  

Java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Bundle containing previous frozen state
        setContentView(R.layout.activity_main);
        
        // The content view pointing to the id of layout
        // in the file activity_main.xml
        Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show();
    }

    protected void onRestart() {
        // It will show a message on the screen
        // then onRestart is invoked
        Toast toast = Toast.makeText(getApplicationContext(), "onRestart Called", Toast.LENGTH_LONG).show();
    }
}
Kotlin
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show()
        }

    override fun onRestart() {
        super.onRestart()
        // It will show a message on the screen
        // then onRestart is invoked
        val toast = Toast.makeText(applicationContext, "onRestart Called", Toast.LENGTH_LONG).show()
    }
}

4. onResume() 

It is invoked when the activity starts interacting with the user. At this point, the activity is at the top of the activity stack, with a user interacting with it. Always followed by onPause() when the activity goes into the background or is closed by the user. 

Example:  

Java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.example.share.R;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        
        // Bundle containing previous frozen state
        super.onCreate(savedInstanceState);

        // The content view pointing to the id of layout
        // in the file activity_main.xml
        setContentView(R.layout.activity_main);

        Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show();
    }

    protected void onResume() {
        // It will show a message on the screen
        // then onResume is invoked
        Toast toast = Toast.makeText(getApplicationContext(), "onResume Called", Toast.LENGTH_LONG).show();
    }
}
Kotlin
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show()
        }

    override fun onResume() {
        super.onResume()
        // It will show a message on the screen
        // then onResume is invoked
        val toast = Toast.makeText(applicationContext, "onResume Called", Toast.LENGTH_LONG).show()
    }
}

5. onPause() 

It is invoked when an activity is going into the background but has not yet been killed. It is a counterpart to onResume(). When an activity is launched in front of another activity, this callback will be invoked on the top activity (currently on screen). The activity, under the active activity, will not be created until the active activity’s onPause() returns, so it is recommended that heavy processing should not be done in this part. 

Example:  

Java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // Bundle containing previous frozen state
        super.onCreate(savedInstanceState);

        // The content view pointing to the id of layout
        // in the file activity_main.xml
        setContentView(R.layout.activity_main);

        Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show();
    }

    protected void onPause() {
        // It will show a message on the screen
        // then onPause is invoked
        Toast toast = Toast.makeText(getApplicationContext(), "onPause Called", Toast.LENGTH_LONG).show();
    }
}
Kotlin
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show()
        }

    override fun onPause() {
        super.onPause()
        // It will show a message on the screen
        // then onPause is invoked
        val toast = Toast.makeText(applicationContext, "onPause Called", Toast.LENGTH_LONG).show()
    }
}

6. onStop()

It is invoked when the activity is not visible to the user. It is followed by onRestart() when the activity is revoked from the background, followed by onDestroy() when the activity is closed or finished, and nothing when the activity remains on the background only. Note that this method may never be called, in low memory situations where the system does not have enough memory to keep the activity’s process running after its onPause() method is called.  

Example:  

Java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // Bundle containing previous frozen state
        super.onCreate(savedInstanceState);

        // The content view pointing to the id of layout
        // in the file activity_main.xml
        setContentView(R.layout.activity_main);

        Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show();
    }

    protected void onStop() {
        // It will show a message on the screen
        // then onStop is invoked
        Toast toast = Toast.makeText(getApplicationContext(), "onStop Called", Toast.LENGTH_LONG).show();
    }
}
Kotlin
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show()
        }

    override fun onStop() {
        super.onStop()
        // It will show a message on the screen
        // then onStop is invoked
        val toast = Toast.makeText(applicationContext, "onStop Called", Toast.LENGTH_LONG).show()
    }
}

7. onDestroy() 

The final call received before the activity is destroyed. This can happen either because the activity is finishing (when finish() is invoked) or because the system is temporarily destroying this instance of the activity to save space. To distinguish between these scenarios, check it with isFinishing() method.  

Example:

Java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        
        // Bundle containing previous frozen state
        super.onCreate(savedInstanceState);

        // The content view pointing to the id of layout
        // in the file activity_main.xml
        setContentView(R.layout.activity_main);

        Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show();
    }

    protected void onDestroy() {
        // It will show a message on the screen
        // then onDestroy is invoked
        Toast toast = Toast.makeText(getApplicationContext(), "onDestroy Called", Toast.LENGTH_LONG).show();
    }
}
Kotlin
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show()
        }

    override fun onDestroy() {
        super.onDestroy()
        // It will show a message on the screen
        // then onDestroy is invoked
        val toast = Toast.makeText(applicationContext, "onDestroy Called", Toast.LENGTH_LONG).show()
    }
}

Demo Android App to Demonstrate Activity Lifecycle in Android

Java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show();
    }

    protected void onStart() {
        super.onStart();
        Toast toast = Toast.makeText(getApplicationContext(), "onStart Called", Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Toast toast = Toast.makeText(getApplicationContext(), "onRestart Called", Toast.LENGTH_LONG).show();
    }

    protected void onPause() {
        super.onPause();
        Toast toast = Toast.makeText(getApplicationContext(), "onPause Called", Toast.LENGTH_LONG).show();
    }

    protected void onResume() {
        super.onResume();
        Toast toast = Toast.makeText(getApplicationContext(), "onResume Called", Toast.LENGTH_LONG).show();
    }

    protected void onStop() {
        super.onStop();
        Toast toast = Toast.makeText(getApplicationContext(), "onStop Called", Toast.LENGTH_LONG).show();
    }

    protected void onDestroy() {
        super.onDestroy();
        Toast toast = Toast.makeText(getApplicationContext(), "onDestroy Called", Toast.LENGTH_LONG).show();
    }
}
Kotlin
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show()
        }

    override fun onStart() {
        super.onStart()
        val toast = Toast.makeText(applicationContext, "onStart Called", Toast.LENGTH_LONG).show()
    }

    override fun onRestart() {
        super.onRestart()
        val toast = Toast.makeText(applicationContext, "onRestart Called", Toast.LENGTH_LONG).show()
    }

    override fun onPause() {
        super.onPause()
        val toast = Toast.makeText(applicationContext, "onPause Called", Toast.LENGTH_LONG).show()
    }

    override fun onResume() {
        super.onResume()
        val toast = Toast.makeText(applicationContext, "onResume Called", Toast.LENGTH_LONG).show()
    }

    override fun onStop() {
        super.onStop()
        val toast = Toast.makeText(applicationContext, "onStop Called", Toast.LENGTH_LONG).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        val toast = Toast.makeText(applicationContext, "onDestroy Called", Toast.LENGTH_LONG).show()
    }
}

Output: 



Previous Article
Next Article

Similar Reads

Understanding Activity Lifecycle to Retain UI Data when Back Pressed in Android
What is onBackPressed() in Android? This is an override function called when the user presses the back button on an Android device. It has great implications on the activity lifecycle of the application. The official documentation states that onBackPressed() method is called when the activity has detected the user's press of the back key. The defau
5 min read
How to Pass a Serializable Object from One Activity to Another Activity in Android?
While developing an application in Android, the developer can create more than one activity in the application. So, there can be many activities and can be a case to transfer data from one activity to the other. In such cases, Intents are used. Intents let the user jump from one activity to the other, or go from the current activity to the next act
4 min read
How to Send Data From One Activity to Second Activity in Android?
This article aims to tell and show how to "Send the data from one activity to second activity using Intent" . In this example, we have two activities, activity_first which are the source activity, and activity_second which is the destination activity. We can send the data using the putExtra() method from one activity and get the data from the secon
7 min read
How to Use Android Sliding Activity Library in Android App?
Sliding activities allow you to easily set header content, menus, and data onto slidable screens. Easily create activities that can slide vertically on the screen and fit well into the material design age. We can set header images to our sliding activity. We can also customize the color that will affect the header and the status bar. We can also di
3 min read
How to Send Image File from One Activity to Another Activity?
In this article, we are going to send an image from one activity to another. We will be using putExtra to send image and we will be using bundle to get the data sent from the previous activity and then we will be showing the received image. Step by Step Implementation Step 1: Create a New Project To create a new project in Android Studio please ref
3 min read
Intent Filter in Android with Demo App
The intent is a messaging object which tells what kind of action to be performed. The intent’s most significant use is the launching of the activity. Intent facilitates the communication between the components. Note: App components are the basic building blocks of App. Fundamental use case of Intents Starting Activity An activity represents the sin
5 min read
Processes and Application Lifecycle in Android
As an android developer, if one does not know the application lifecycle of android application or does not have in-depth knowledge about it, there are very high chances that the application will not have a good user experience. Not having proper knowledge of the application lifecycle will not affect the working of that application but it will lead
7 min read
Lifecycle in Android Architecture Components
Lifecycle is one of the Android Architecture Components which was released by Google to make it easier for all the Android developers. The Lifecycle is a class/interface which holds the information about the state of an activity/fragment and also it allows other objects to observe this state by keeping track of it. The LifeCycle component is concer
4 min read
Fragment Lifecycle in Android
In Android, the fragment is the part of the Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the Android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. The UI flexibility on all devices improves the user exp
8 min read
Android - You need to use a Theme.AppCompat theme (or descendant) with this activity
You need to use a Theme.AppCompat theme (or descendant) with this activity is a common error message that appears when trying to run an Android application. This error occurs because the Android operating system requires the use of a specific theme for the application's main activity. In this article, we'll explore the cause of this error and the s
4 min read
Activity State Changes In Android with Example
Prerequisites: Activity lifecycle in android As it is known that every Android app has at least one activity associated with it. When the application begins to execute and runs, there are various state changes that activity goes through. Different events some user-triggered and some system triggered can cause an activity to do the transition from o
6 min read
How to Create Constructor, Getter/Setter Methods and New Activity in Android Studio using Shortcuts?
Android Studio is the official integrated development environment for Google's Android operating system, built on JetBrains' IntelliJ IDEA software and designed specifically for Android development. In this article we are going to discuss the following three things: Create a Constructor for Class in Android Studio using ShortcutsCreate a Getter/Set
3 min read
Different Ways to Fix "Error type 3 Error: Activity class {} does not exist" in Android Studio
Whenever we try to launch an activity we encounter the error "Error type 3: Activity class {} does not exist" in the Android Studio. The MainActivity Page throws the error as: Error while executing: am start -n “LauncherActivity” -a android.intent.action.MAIN -c android.intent.category.LAUNCHER Starting: intent { act=android.intent.action.MAIN cat=
3 min read
Different Ways to fix “Default Activity Not Found” Issue in Android Studio
This is the most common issue faced by so many developers when creating a new Android Studio Project. This issue occurs because Android Studio was not able to detect the default MainActivity in your Android Studio Project. In this article, we will take a look at four different ways with which we can fix this error in your Android Project. Pre Requi
3 min read
How to Create a Transparent Activity in Android?
Many times we have to display a feature in our app where we have to use transparent activity inside our android app. In this article, we will take a look at creating a Transparent Activity in Android. What we are going to build in this article? We will be building a simple application in which we will be displaying a simple TextView inside a transp
3 min read
How to Create Splash Screen Without an Extra Activity in Android?
A splash screen is the first screen of the app when it is opened. It is used to display some basic introductory information such as the company logo, content, etc just before the app loads completely. In this article, we will follow the best practice to create a Splash screen that is without creating an extra activity for it and it will be gone as
3 min read
What is Android Activity "launchMode"?
Launch mode is an Android OS command that determines how the activity should be started. It specifies how every new action should be linked to the existing task. Before proceeding, you must first grasp the following critical topics: TasksBack StackTypes of Launch Modes for Activities Without further ado, coming to the topic, we will be seeing that
4 min read
How to Stop EditText from Gaining Focus at Activity Startup in Android?
When working on an Android Project, you might face a hazy error, the activity starts, and then the EditText immediately gets the focus and the soft keyboard is forced open. Well, that's not something that we expect, and let's address this, and get rid of it! Method #1: Removing the Request Focus from the EditText You may force override the focus of
2 min read
Difference Between Foreground Service vs Activity in Android
A Service is a component of an application that may conduct long-running activities in the background. It does not have a graphical user interface. A service that has been started may continue to run for some time after the user changes to another program. A component can also bind to a service in order to communicate with it and even execute inter
3 min read
Activity Aliases in Android to Preserve Launchers
Before moving on to the topic, pick up your mobile phones and count the number of applications that you are having on your device. All of you must have more than 30 applications on average. But out of these 30 apps, we only use 5–6 applications on a regular basis. Other applications are rarely used but are important. So, what we do is, create short
7 min read
Activity Recognition in Android
In this article, we are going to learn about an API called the Activity Recognition Transition API or Transition API which is intended for detecting the activity of a particular user such as driving, walking or running, etc. There are many applications that use this Activity Recognition Transition API. For example, a kilometer finder app starts run
8 min read
Send Multiple Data From One Activity to Another in Android using Kotlin
There are multiple ways for sending multiple data from one Activity to Another in Android, but in this article, we will do this using Bundle. Bundle in android is used to pass data from one activity to another, it takes data in key and value pairs. To understand this concept we will create a simple project in android studio using Kotlin. Step by St
3 min read
How to Remove Title Bar From the Activity in Android?
Android Title Bar or ActionBar or Toolbar is the header of any screen in an App. We usually keep fixed title names for every Activity. Sometimes, it is necessary to remove the bar from the activity. There are several ways of doing this. One is if we want to remove the title in all the activities, then we need to go to res > values > themes
2 min read
How to Restart Activity in Android?
An Activity in Android is that element of the application that provides a platform for drawing UI elements. Activity, in general, occupies the entire screen but may not always fill the entire screen. MainActivity is the first activity that is created when a project is created. However, activities can be created later and set as the first activity v
3 min read
Start a New Activity using Intent in Android using Jetpack Compose
In Android OS, an Intent is a mechanism used to navigate a user to another activity or application to achieve a specific task. In general, Intents are used to progress to the next activity or come back to the previous activity. In this article, we will show you how you could start a New Activity using Intent in Android using Jetpack Compose. Follow
4 min read
How to Go Back to Previous Activity in Android?
In this article, we are going to see how we can add a back button to an activity through which we can go back to its previous activity. This can be achieved with just a few lines of code, which is explained in the steps below Step by Step ImplementationStep 1: Create a New Project in Android StudioTo create a new project in Android Studio please re
3 min read
How to Change Application's Starting Activity in Android?
Many times while building an android application. We have to change the default activity of our application to another activity that we have created within our android studio project. So that we can set that custom activity to the starting activity of our application. In this article, we will take a look at the How to Change Applications starting a
2 min read
Android - Pass Parcelable Object From One Activity to Another Using PutExtra
In this article, we are going to see how can we pass a Parcelable object from one activity to another activity and display the data on the second activity. To pass a Parcelable object from one activity to another in Android, we can use the putExtra() method of the Intent class and pass in the object as an argument to the second activity. For Exampl
9 min read
Android - Crash in Activity Transitions with SharedElement
Shared element transition is a powerful animation feature in Android that allows developers to create a seamless transition between different elements in their app, giving the illusion of a smooth flow between screens. However, sometimes the transition may not work as expected, and the animation may appear glitchy or simply not function at all. In
4 min read
Activity Transition in Android
The term "Android activity transitions" refers to a complex and multifaceted set of processes and mechanisms that are developed when moving between two distinct activities within an Android application. The goal of these transitions is to enhance an experience that is both seamlessly integrated such that the user is able to effortlessly glide betwe
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg