Activity Lifecycle: Activity is one of the building blocks of Android OS. In simple words Activity is a screen that user interact with. Every Activity in android has lifecycle like created, started, resumed, paused, stopped or destroyed. These different states are known as Activity Lifecycle. In other words we can say Activity is a class pre-written in Java Programming.
Table Of Contents
Short description of Activity Lifecycle example:
onCreate() – Called when the activity is first created
onStart() – Called just after it’s creation or by restart method after onStop(). Here Activity start becoming visible to user
onResume() – Called when Activity is visible to user and user can interact with it
onPause() – Called when Activity content is not visible because user resume previous activity
onStop() – Called when activity is not visible to user because some other activity takes place of it
onRestart() – Called when user comes on screen or resume the activity which was stopped
onDestroy – Called when Activity is not in background
Activity have different states or it’s known as Activity life cycle. All life cycle methods aren’t required to override but it’s quite important to understand them. Lifecycles methods can be overridden according to requirements.
LIST OF ACTIVITY LIFECYCLE METHODS OR STATES:
Activity Created: onCreate(Bundle savedInstanceState):
onCreate() method is called when activity gets memory in the OS. To use create state we need to override onCreate(Bundle savedInstanceState) method. Now there will be question in mind what is Bundle here, so Bundle is a data repository object that can store any kind of primitive data and this object will be null until some data isn’t saved in that.
Learn More About onCreate(Bundle savedInstanceState) With Example
Activity Started: onStart():
onStart() method is called just after it’s creation. In other case Activity can also be started by calling restart method i.e after activity stop. So this means onStart() gets called by Android OS when user switch between applications. For example, if a user was using Application A and then a notification comes and user clicked on notification and moved to Application B, in this case Application A will be paused. And again if a user again click on app icon of Application A then Application A which was stopped will again gets started.
Learn More About onStart() With Example
Activity Resumed:.onResume():
Activity resumed is that situation when it is actually visible to user means the data displayed in the activity is visible to user. In lifecycle it always gets called after activity start and in most use case after activity paused (onPause).
Activity Paused: onPause():
Activity is called paused when it’s content is not visible to user, in most case onPause() method called by Android OS when user press Home button (Center Button on Device) to make hide.
Activity also gets paused before stop called in case user press the back navigation button. The activity will go in paused state for these reasons also if a notification or some other dialog is overlaying any part (top or bottom) of the activity (screen). Similarly, if the other screen or dialog is transparent then user can see the screen but cannot interact with it. For example, if a call or notification comes in, the user will get the opportunity to take the call or ignore it.
Learn More About onPause() With Example
Activity Stopped: onStop():
Activity is called stopped when it’s not visible to user. Any activity gets stopped in case some other activity takes place of it. For example, if a user was on screen 1 and click on some button and moves to screen 2. In this case Activity displaying content for screen 1 will be stopped.
Every activity gets stopped before destroy in case of when user press back navigation button. So Activity will be in stopped state when hidden or replaced by other activities that have been launched or switched by user. In this case application will not present anything useful to the user directly as it’s going to stop.
Learn More About onStop() With Example
Activity Restarted: onRestart():
Activity is called in restart state after stop state. So activity’s onRestart() function gets called when user comes on screen or resume the activity which was stopped. In other words, when Operating System starts the activity for the first time onRestart() never gets called. It gets called only in case when activity is resumes after stopped state.
Activity Destroyed: onDestroy():
Any activity is known as in destroyed state when it’s not in background. There can different cases at what time activity get destroyed.
First is if user pressed the back navigation button then activity will be destroyed after completing the lifecycle of pause and stop.
In case if user press the home button and app moves to background. User is not using it no more and it’s being shown in recent apps list. So in this case if system required resources need to use somewhere else then OS can destroy the Activity.
After the Activity is destroyed if user again click the app icon, in this case activity will be recreated and follow the same lifecycle again. Another use case is with Splash Screens if there is call to finish() method from onCreate() of an activity then OS can directly call onDestroy() with calling onPause() and onStop().
In the below example we have used the below JAVA and Android topics:
JAVA Topics Used: Method Overriding, static variable, package, Inheritance, method and class.
Android Topic Used: We have used Log class which is used to printout message in Logcat. One of the important use of Log is in debugging.
First we will create a new Android Project and name the activity as HomeActivity. In our case we have named our App project as Activity Lifecycle Example.
We will initialize a static String variable with the name of the underlying class using getSimpleName() method. In our case HOME_ACTIVITY_TAG is the name of the String variable which store class name HomeActivity.
private static final String HOME_ACTIVITY_TAG = HomeActivity.class.getSimpleName();
Now we will create a new method which will print message in Logcat.
private void showLog(String text){ Log.d(HOME_ACTIVITY_TAG, text); }
Now we will override all activity lifecycle method in Android and use showLog() method which we creating for printing message in Logcat.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); showLog("Activity Created"); } @Override protected void onRestart(){ super.onRestart();//call to restart after onStop showLog("Activity restarted"); } @Override protected void onStart() { super.onStart();//soon be visible showLog("Activity started"); } @Override protected void onResume() { super.onResume();//visible showLog("Activity resumed"); } @Override protected void onPause() { super.onPause();//invisible showLog("Activity paused"); } @Override protected void onStop() { super.onStop(); showLog("Activity stopped"); } @Override protected void onDestroy() { super.onDestroy(); showLog("Activity is being destroyed"); }
Complete JAVA code of HomeActivity.java:
package com.abhiandroid.activitylifecycleexample; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; public class HomeActivity extends AppCompatActivity { private static final String HOME_ACTIVITY_TAG = HomeActivity.class.getSimpleName(); private void showLog(String text){ Log.d(HOME_ACTIVITY_TAG, text); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); showLog("Activity Created"); } @Override protected void onRestart(){ super.onRestart();//call to restart after onStop showLog("Activity restarted"); } @Override protected void onStart() { super.onStart();//soon be visible showLog("Activity started"); } @Override protected void onResume() { super.onResume();//visible showLog("Activity resumed"); } @Override protected void onPause() { super.onPause();//invisible showLog("Activity paused"); } @Override protected void onStop() { super.onStop(); showLog("Activity stopped"); } @Override protected void onDestroy() { super.onDestroy(); showLog("Activity is being destroyed"); } }
When creating an Activity we need to register this in AndroidManifest.xml file. Now question is why need to register? Its actually because manifest file has the information which Android OS read very first. When registering an activity other information can also be defined within manifest like Launcher Activity (An activity that should start when user click on app icon).
Here is declaration example in AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.abhiandroid.homeactivity"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".HomeActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Output Of Activity Lifecycle:
When you will run the above program you will notice a blank white screen will open up in Emulator. You might be wondering where is default Hello world screen. Actually we have removed it by overriding onCreate() method. Below is the blank white screen that will pop up.
Now press the back button on the Emulator and exit the App:
So this clears:
Important Note: In the above example onRestart() won’t be called because there was no situation when we can resume the onStart() method again. In future example we will show you onRestart() in action as well.
Activity is the main component of Android Application, as every screen is an activity so to create any simple app first we have to start with Activities. Every lifecycle method is quite important to implement according to requirements, However onCreate(Bundle state) is always needed to implement to show or display some content on screen.
Premium Project Source Code:
this is very improtent information for beginner to intermediate level lerner.
By my opinion it is very importetn content for me because i also want to know about this topic.
I happy and get boot from this information.
than abhishek for this information
keep it up.
Hi Abhishek Saini Vaiya,
I hope that you are doing well. I am from Bangladesh. My name is Jahangir Alom Minto. I am learning Android App Development. I always follow your abhiandroid.com site. This is just a great resource and your Master Android Development ebook also a great material for android learners.
Thank you so much for your great mind and free contribution to Android Learning.
Best Regards
Jahangir Alom Minto
its very good information.For beginners this information is enough to get job.