Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Android Lifecycle  
3.
Lifecycle callbacks
4.
onCreate()
5.
onStart()
6.
onResume()
7.
onPause()
8.
onStop()
9.
onDestroy()
10.
Frequently Asked Questions
10.1.
What is the difference between onCreate() and onStart() callback?
10.2.
What callback is necessary to be implemented?
10.3.
What event occurs when a call comes in the middle of video streaming?
10.4.
Which callback is called when an application ends?
10.5.
Name two components that are associated with lifecycle callbacks?
11.
Conclusion
Last Updated: Mar 27, 2024

Activity-lifecycle Events

gp-icon
Fundamentals of react native
Free guided path
7 chapters
15+ problems
gp-badge
Earn badges and level up

Introduction

Android is a smartphone and tablet operating system based on a modified version of the Linux kernel as well as other open-source software. Google commercially sponsors Android, which is developed by a group of developers known as the Open Handset Alliance. The Android Software Development Kit is used to create Android applications, which are usually written in Java. It facilitates development by utilizing programming languages such as Java and Kotlin. Every Android application is made up of Activities (which are similar to web pages on a website) and Fragments, which render the app's view.

Android Lifecycle  

Every Activity or the Fragment Instance has its own lifecycle. These instances in your app migrate through multiple states in their lifetime when a user navigates through, out of, and back to your app.
The Activity class supports a number of callbacks that let the activity know when a state has changed, such as when the system is creating, pausing, or restarting an activity, or when the process in which the activity resides is being destroyed.
A core set of six callbacks is provided by the Activity class:

Source

Figure 1. Activity lifecycle events illustration. 

When an activity changes state, the system calls each of these callbacks. Fragment implements LifecycleOwner to manage the lifecycle, exposing a Lifecycle object that can be accessed via the getLifecycle() method. The Lifecycle represents every possible Lifecycle.State enum.

Instead of using a LifecycleObserver, the Fragment class also includes callback methods for each change in a fragment's lifecycle. Among them are:

Source

Figure 2. Fragment Lifecycle states and their connections to the fragment's lifecycle callbacks and the fragment's view Lifecycle.

Lifecycle callbacks

Lifecycle callback allows how the activity should behave when the user exits and re-enters it using these methods. When a user switches to another app, the video must be paused, and the network connection should be disconnected if you're making a streaming video player. When the user returns, you can reconnect to the network and let them pick up where they left off with the video. In other words, each callback enables you to perform specific work in response to a specific state change. Doing the right thing at the right time and properly handling transitions make your app more robust and performant.

Refer this to know about, android operating system

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

onCreate()

This callback is triggered when the system first creates the activity, and it must be implemented. When an activity is created, it enters the Created state. The basic application startup logic in the onCreate() method, should only happen once for the duration of the activity. For example, your onCreate() implementation could bind data to lists, associate the activity with a ViewModel, and instantiate some class-scope variables.

The activity isn't in the Created state. The activity enters the Started state after the onCreate() method completes execution, and the system calls the onStart() and onResume() methods in quick succession.

public class MainActivity extends AppCompatActivity {

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

onStart()

When the activity enters the Started state, the system calls this callback. The app is getting ready for the activity to come to the foreground and become interactive, the onStart() call makes it visible to the user. This method, for example, is where the app initializes the code that maintains the UI. 
When the activity enters the started state, any lifecycle-aware component associated with the activity's lifecycle receives the ON_START event. 
The onStart() method completes quickly, and the activity, like the Created state, does not remain in the Started state. When this callback completes, the activity is resumed, and the system calls the onResume() method.

onResume()

When an activity enters the Resumed state, it is brought to the foreground, and the system calls the onResume() callback. This is the mode in which the app communicates with the user. The app remains in this state until something happens to divert attention away from it. Receiving a phone call, switching to another activity, or turning off the device screen are all examples of such events.

When the activity is resumed, any lifecycle-aware component associated with the activity's lifecycle will receive the ON_RESUME event. This is where lifecycle components can enable any functionality that requires the component to run in the foreground while it is visible, such as starting a camera preview. As a result, you should implement onResume() to initialize components that you released during onPause(), as well as any other initializations that must occur each time the activity enters the Resumed state.

class MainActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        }
 
    override fun onResume() {
        super.onResume()
    }
}

onPause()

This method is the first indication that the user is leaving your activity (though it does not always imply that it is being destroyed); it indicates that the activity has been moved to the background. While the Activity is in the Paused state and will be resumed soon, use the onPause() method to pause or adjust operations that should not be done (or should only be done in moderation). A variety of factors can cause an activity to enter this state. Consider the following scenario:

  • Some events, as described in the onResume() section, cause app execution to be interrupted. This is the most common situation.
  • Multiple apps can run in multi-window mode in Android 7.0 (API level 24) or higher. Because only one app (windows) has focus at any given time, the system pauses all other apps.
  • A new, semi-transparent activity (such as a conversation) begins. The activity remains paused as long as it is partially visible but not in focus.

When the activity enters the paused state, any lifecycle-aware component associated with the activity's lifecycle receives the ON_PAUSE event. Lifecycle components can halt any functionality that does not need to run while the component is not in the foreground, such as a camera preview.

class MainActivity : AppCompatActivity() {

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

	override fun onPause() {
		super.onPause()
	}
}

The completion of the onPause() method does not indicate that the activity has exited the Paused state. Rather, the activity will remain in this state until it either resumes or becomes completely invisible to the user.

onStop()

When a user can no longer see your activity, it enters the Stopped state, and the system calls the onStop() callback. This can happen when a newly opened activity takes up the full screen, for example. When the activity has finished operating and is going to be stopped, the system may call onStop(). 
Any lifecycle-aware component attached to the activity's lifecycle will get the ON_STOP event when the activity enters the stopped state. While the component is not visible on the screen, the lifecycle components can cease any behavior that does not need to run.

class MainActivity : AppCompatActivity() {

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


	override fun onStop() {
		super.onStop()
	}
}

While the app is not visible to the user, the onStop() method should be used to release or adjust resources that are no longer needed. Your app may, for example, pause animations or switch from fine to coarse location updates. When you use onStop() instead of onPause(), your UI-related work continues even if the user is viewing your activity in multi-window mode.

The activity either returns to the Stopped state to interact with the user, or it finishes running and disappears. The system calls onRestart() if the activity returns. When the Activity has completed its execution, the system calls onDestroy(). The onDestroy() callback is explained in the following section.

onDestroy()

Before the activity is destroyed, onDestroy() is called. This callback is triggered by the system for one of two reasons:

  1. the activity is ending (either because the user has completely dismissed it or because finish() has been called on it), or
  2. Due to a configuration change, the system is temporarily destroying the activity (such as device rotation or multi-window mode)

Any lifecycle-aware component connected to the activity's lifecycle will receive the ON_DESTROY event when the activity moves to the destroyed state. Before the Activity is destroyed, the lifecycle components can clean up any debris. 
The onDestroy() callback should release any resources that haven't been released yet by other callbacks, such as onStop().

class MainActivity : AppCompatActivity() {

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

	override fun onDestroy() {
		super.onDestroy()
	}
}

Frequently Asked Questions

What is the difference between onCreate() and onStart() callback?

onCreate() is triggered when the system first creates the activity whereas the onStart() is automatically called after onCreate()

What callback is necessary to be implemented?

onCreate() is necessary to implement. This specifies what is a necessary task/rendering to be done whenever the application is started.

What event occurs when a call comes in the middle of video streaming?

When a call is received, the already running application will receive the ON_PAUSE event. 

Which callback is called when an application ends?

onDestroy() is called automatically when the application is closed. The memory and resources associated with it are deallocated.

Name two components that are associated with lifecycle callbacks?

Activities and Fragments are two Android components that have a lifecycle associated with them.

Conclusion

In this article, we had a look at Android Lifecycle events and their importance in creating an application. We also learned how these events behave in different events. We hope that this blog has helped you enhance your knowledge regarding the Android lifecycle, and if you would like to learn more, check out the Android Architecture and Activities in Android articles on Coding Ninjas Studio. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Android App Resources
Next article
Android Services
Guided path
Free
gridgp-icon
Fundamentals of react native
7 chapters
15+ Problems
gp-badge
Earn badges and level up
Live masterclass