{"id":290,"date":"2015-12-12T09:11:17","date_gmt":"2015-12-12T09:11:17","guid":{"rendered":"http:\/\/abhiandroid.com\/programming\/?page_id=290"},"modified":"2018-06-06T04:31:46","modified_gmt":"2018-06-06T04:31:46","slug":"activity-life-cycle","status":"publish","type":"page","link":"https:\/\/abhiandroid.com\/programming\/activity-life-cycle","title":{"rendered":"Activity Lifecycle With Example In Android &#8211; Tutorial, Code And Importance"},"content":{"rendered":"<p><span style=\"color: #008000;\"><strong>Activity Lifecycle: <\/strong><\/span>Activity is one of the building blocks of Android OS. In simple words Activity is a screen that user interact with. <em>Every Activity in android has lifecycle like created, started, resumed, paused, stopped or destroyed. These different states are known as Activity Lifecycle.<\/em> In other words we can say Activity is a class pre-written in Java Programming.<\/p>\n<h4><strong>Below is Activity Lifecycle Table:<\/strong><\/h4>\n<p>Short description of Activity Lifecycle example:<\/p>\n<p><strong>onCreate() &#8211;<\/strong> Called when the activity is first created<\/p>\n<p><strong>onStart() &#8211;<\/strong> Called just after it\u2019s creation or by restart method after onStop(). Here Activity start becoming visible to user<\/p>\n<p><strong>onResume() &#8211;<\/strong> Called when Activity is visible to user and user can interact with it<\/p>\n<p><strong>onPause() &#8211;<\/strong> Called when Activity content is not visible because user resume previous activity<\/p>\n<p><strong>onStop() &#8211;<\/strong> Called when activity is not visible to user because some other activity takes place of it<\/p>\n<p><strong>onRestart() &#8211;<\/strong> Called when user comes on screen or resume the activity which was stopped<\/p>\n<p><strong>onDestroy &#8211;<\/strong> Called when Activity is not in background<\/p>\n<hr \/>\n<h4><strong>Below Activity Lifecycle Diagram Shows Different States:<\/strong><\/h4>\n<p><center><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-309\" src=\"\/programming\/wp-content\/uploads\/2015\/12\/Activity-Lifecycle-Diagram.jpg\" alt=\"Activity Lifecycle Diagram\" width=\"520\" height=\"287\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Activity-Lifecycle-Diagram.jpg 520w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Activity-Lifecycle-Diagram-300x166.jpg 300w\" sizes=\"auto, (max-width: 520px) 100vw, 520px\" \/><\/center><\/p>\n<hr \/>\n<h4><strong>Different Types of Activity Lifecycle States:<\/strong><\/h4>\n<p>Activity have different states or it\u2019s known as Activity life cycle. All life cycle methods aren\u2019t required to override but it&#8217;s quite important to understand them. Lifecycles methods can be overridden according to requirements.<\/p>\n<p><span style=\"text-decoration: underline; color: #008000;\"><strong>LIST OF ACTIVITY LIFECYCLE METHODS OR STATES:<\/strong><\/span><\/p>\n<p><span style=\"color: #993366;\"><strong>Activity Created: onCreate(Bundle savedInstanceState):<\/strong><\/span><\/p>\n<p>onCreate() method is called when activity gets memory in the OS. <strong>To use create state we need to override onCreate(Bundle savedInstanceState) method.<\/strong> 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\u2019t saved in that.<\/p>\n<ul>\n<li>When an Activity first call or launched then onCreate(Bundle savedInstanceState) method is responsible to create the activity.<\/li>\n<li>When ever orientation(i.e. from horizontal to vertical or vertical to horizontal) of activity gets changed or when an Activity gets forcefully terminated by any Operating System then savedInstanceState i.e. object of Bundle Class will save the state of an Activity.<\/li>\n<li>It is best place to put initialization code.<\/li>\n<\/ul>\n<p>Learn More About <a href=\"\/programming\/oncreate-activity-android.html\">onCreate(Bundle savedInstanceState) With Example<\/a><\/p>\n<p><span style=\"color: #993366;\"><strong>Activity Started: onStart():<\/strong><\/span><\/p>\n<p>onStart() method is called just after it\u2019s 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.<\/p>\n<p>Learn More About <a href=\"\/programming\/onstart-method-in-android.html\">onStart() With Example<\/a><\/p>\n<p><span style=\"color: #993366;\"><strong>Activity Resumed:<\/strong>.<strong>onResume():<\/strong><\/span><\/p>\n<p>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 (<strong>onPause<\/strong>).<\/p>\n<p><span style=\"color: #993366;\"><strong>Activity Paused: onPause():<\/strong><\/span><\/p>\n<p>Activity is called paused when it\u2019s 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.<\/p>\n<p>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.<\/p>\n<p>Learn More About <a href=\"\/programming\/onpause-tutorial-examples.html\">onPause() With Example<\/a><\/p>\n<p><span style=\"color: #993366;\"><strong>Activity Stopped: onStop():<\/strong><\/span><\/p>\n<p>Activity is called stopped when it\u2019s 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.<\/p>\n<p>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\u2019s going to stop.<\/p>\n<p>Learn More About <a href=\"\/programming\/onstop-tutorial-example.html\">onStop() With Example<\/a><\/p>\n<p><span style=\"color: #993366;\"><strong>Activity Restarted: onRestart():<\/strong><\/span><\/p>\n<p>Activity is called in restart state after stop state. So activity\u2019s 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.<\/p>\n<p><span style=\"color: #993366;\"><strong>Activity Destroyed: onDestroy():<\/strong><\/span><\/p>\n<p>Any activity is known as in destroyed state when it\u2019s not in background. There can different cases at what time activity get destroyed.<\/p>\n<p>First is if user pressed the back navigation button then activity will be destroyed after completing the lifecycle of pause and stop.<\/p>\n<p>In case if user press the home button and app moves to background. User is not using it no more and it\u2019s 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.<\/p>\n<p>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().<\/p>\n<hr \/>\n<h4><strong>Activity Lifecycle Example:<\/strong><\/h4>\n<p>In the below example we have used the below JAVA and Android topics:<\/p>\n<p><span style=\"color: #008000;\"><strong>JAVA Topics Used:<\/strong><\/span> Method Overriding, <a href=\"\/java\/types-of-variables.html\">static variable<\/a>, package, Inheritance, method and class.<\/p>\n<p><span style=\"color: #008000;\"><strong>Android Topic Used:<\/strong><\/span> We have used Log class which is used to printout message in Logcat. One of the important use of Log is in debugging.<\/p>\n<p>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.<\/p>\n<p>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.<\/p>\n<pre>private static final String HOME_ACTIVITY_TAG = HomeActivity.class.getSimpleName();<\/pre>\n<p>Now we will create a new method which will print message in Logcat.<\/p>\n<pre>private void showLog(String text){\r\n\r\n   Log.d(HOME_ACTIVITY_TAG, text);\r\n\r\n}<\/pre>\n<p>Now we will override all activity lifecycle method in Android and use showLog() method which we creating for printing message in Logcat.<\/p>\n<pre>@Override\r\n\r\n    public void onCreate(Bundle savedInstanceState) {\r\n\r\n        super.onCreate(savedInstanceState);\r\n\r\n        showLog(\"Activity Created\");\r\n\r\n    }\r\n\r\n@Override\r\n\r\nprotected void onRestart(){\r\n\r\n    super.onRestart();\/\/call to restart after onStop\r\n\r\n    showLog(\"Activity restarted\");\r\n\r\n}\r\n\r\n@Override\r\n\r\nprotected void onStart() {\r\n\r\n    super.onStart();\/\/soon be visible\r\n\r\n    showLog(\"Activity started\");\r\n\r\n}\r\n\r\n@Override\r\n\r\nprotected void onResume() {\r\n\r\n    super.onResume();\/\/visible\r\n\r\n    showLog(\"Activity resumed\");\r\n\r\n}\r\n\r\n@Override\r\n\r\nprotected void onPause() {\r\n\r\n    super.onPause();\/\/invisible\r\n\r\n    showLog(\"Activity paused\");\r\n\r\n}\r\n\r\n@Override\r\n\r\nprotected void onStop() {\r\n\r\n    super.onStop();\r\n\r\n    showLog(\"Activity stopped\");\r\n\r\n}\r\n\r\n@Override\r\n\r\nprotected void onDestroy() {\r\n\r\n    super.onDestroy();\r\n\r\n    showLog(\"Activity is being destroyed\");\r\n\r\n}<\/pre>\n<p><span style=\"color: #008000;\"><strong>Complete JAVA code of HomeActivity.java:<\/strong><\/span><\/p>\n<pre>package com.abhiandroid.activitylifecycleexample;\r\n\r\nimport android.os.Bundle;\r\nimport android.support.design.widget.FloatingActionButton;\r\nimport android.support.design.widget.Snackbar;\r\nimport android.support.v7.app.AppCompatActivity;\r\nimport android.support.v7.widget.Toolbar;\r\nimport android.util.Log;\r\nimport android.view.View;\r\nimport android.view.Menu;\r\nimport android.view.MenuItem;\r\n\r\n\r\n\r\n    public class HomeActivity extends AppCompatActivity {\r\n\r\n        private static final String HOME_ACTIVITY_TAG = HomeActivity.class.getSimpleName();\r\n\r\n\r\n        private void showLog(String text){\r\n\r\n            Log.d(HOME_ACTIVITY_TAG, text);\r\n\r\n        }\r\n\r\n        @Override\r\n\r\n        public void onCreate(Bundle savedInstanceState) {\r\n\r\n            super.onCreate(savedInstanceState);\r\n\r\n            showLog(\"Activity Created\");\r\n\r\n        }\r\n\r\n        @Override\r\n\r\n        protected void onRestart(){\r\n\r\n            super.onRestart();\/\/call to restart after onStop\r\n\r\n            showLog(\"Activity restarted\");\r\n\r\n        }\r\n\r\n        @Override\r\n\r\n        protected void onStart() {\r\n\r\n            super.onStart();\/\/soon be visible\r\n\r\n            showLog(\"Activity started\");\r\n\r\n        }\r\n\r\n        @Override\r\n\r\n        protected void onResume() {\r\n\r\n            super.onResume();\/\/visible\r\n\r\n            showLog(\"Activity resumed\");\r\n\r\n        }\r\n\r\n        @Override\r\n\r\n        protected void onPause() {\r\n\r\n            super.onPause();\/\/invisible\r\n\r\n            showLog(\"Activity paused\");\r\n\r\n        }\r\n\r\n        @Override\r\n\r\n        protected void onStop() {\r\n\r\n            super.onStop();\r\n\r\n            showLog(\"Activity stopped\");\r\n\r\n        }\r\n\r\n        @Override\r\n\r\n        protected void onDestroy() {\r\n\r\n            super.onDestroy();\r\n\r\n            showLog(\"Activity is being destroyed\");\r\n\r\n        }\r\n\r\n    }<\/pre>\n<p>When creating an Activity we need to register this in AndroidManifest.xml file. Now question is why need to register? <strong>Its actually because manifest file has the information which Android OS read very first.<\/strong> 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).<\/p>\n<p>Here is declaration example in AndroidManifest.xml file<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;manifest xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    package=\"com.abhiandroid.homeactivity\"&gt;\r\n\r\n    &lt;application\r\n        android:allowBackup=\"true\"\r\n        android:icon=\"@mipmap\/ic_launcher\"\r\n        android:label=\"@string\/app_name\"\r\n        android:supportsRtl=\"true\"\r\n        android:theme=\"@style\/AppTheme\"&gt;\r\n        &lt;activity\r\n            android:name=\".HomeActivity\"\r\n            android:label=\"@string\/app_name\"\r\n            android:theme=\"@style\/AppTheme.NoActionBar\"&gt;\r\n            &lt;intent-filter&gt;\r\n                &lt;action android:name=\"android.intent.action.MAIN\" \/&gt;\r\n\r\n                &lt;category android:name=\"android.intent.category.LAUNCHER\" \/&gt;\r\n            &lt;\/intent-filter&gt;\r\n        &lt;\/activity&gt;\r\n    &lt;\/application&gt;\r\n\r\n&lt;\/manifest&gt;<\/pre>\n<p><span style=\"text-decoration: underline; color: #008000;\"><strong>Output Of Activity Lifecycle:<\/strong><\/span><\/p>\n<p>When you will run the above program you will notice a blank white screen will open up in Emulator. <em>You might be wondering where is default Hello world screen. Actually we have removed it by overriding onCreate() method.<\/em> Below is the blank white screen that will pop up.<\/p>\n<p><center><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-303 size-thumbnail\" src=\"\/programming\/wp-content\/uploads\/2015\/12\/Activity-lifecycle-white-screen-150x150.jpg\" alt=\"Activity lifecycle white screen\" width=\"150\" height=\"150\" \/><\/center>Now go to Logcat present inside Android Monitor: Scroll up and you will notice three methods which were called: Activity Created, Activity started and Activity resumed.<\/p>\n<p><center><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-304\" src=\"\/programming\/wp-content\/uploads\/2015\/12\/Activity-Lifecycle-Logcat-Output-oncreate-onstart-onresume.jpg\" alt=\"Activity Lifecycle Logcat Output oncreate() onstart() onresume()\" width=\"847\" height=\"243\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Activity-Lifecycle-Logcat-Output-oncreate-onstart-onresume.jpg 847w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Activity-Lifecycle-Logcat-Output-oncreate-onstart-onresume-300x86.jpg 300w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Activity-Lifecycle-Logcat-Output-oncreate-onstart-onresume-768x220.jpg 768w\" sizes=\"auto, (max-width: 847px) 100vw, 847px\" \/><\/center>So this clears:<\/p>\n<ul>\n<li>first onCreate() method was called when activity was created<\/li>\n<li>second onStart() method was called when activity start becoming visible to user<\/li>\n<li>Finally onResume() method was called when activity is visible to user and user can interact with it<\/li>\n<\/ul>\n<p>Now press the back button on the Emulator and exit the App:<\/p>\n<p><center><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-305\" src=\"\/programming\/wp-content\/uploads\/2015\/12\/press-back-button-Activity-Lifecycle.jpg\" alt=\"press back button Activity Lifecycle\" width=\"210\" height=\"180\" \/><\/center>Go to Logcat again and scroll down to bottom. You will see 3 more methods were called: Activity paused, Activity stopped and Activity is being destroyed.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-306 size-full\" src=\"\/programming\/wp-content\/uploads\/2015\/12\/Activity-Lifecycle-Logcat-Output-onpause-onstop-ondestroy.jpg\" alt=\"Activity Lifecycle Logcat Output onpause() onstop() ondestroy()\" width=\"879\" height=\"233\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Activity-Lifecycle-Logcat-Output-onpause-onstop-ondestroy.jpg 879w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Activity-Lifecycle-Logcat-Output-onpause-onstop-ondestroy-300x80.jpg 300w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Activity-Lifecycle-Logcat-Output-onpause-onstop-ondestroy-768x204.jpg 768w\" sizes=\"auto, (max-width: 879px) 100vw, 879px\" \/><\/p>\n<p>So this clears:<\/p>\n<ul>\n<li>onPause() method was called when user resume previous activity<\/li>\n<li>onStop() method was called when activity is not visible to user<\/li>\n<li>Last onDestroy() method was called when Activity is not in background<\/li>\n<\/ul>\n<p><span style=\"color: #ff0000;\"><strong>Important Note:<\/strong><\/span> In the above example onRestart() won&#8217;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.<\/p>\n<hr \/>\n<h4><strong>Importance Of Activity Life Cycle:<br \/>\n<\/strong><\/h4>\n<p>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.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 &hellip; <a href=\"https:\/\/abhiandroid.com\/programming\/activity-life-cycle\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Activity Lifecycle With Example In Android &#8211; Tutorial, Code And Importance<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":309,"parent":0,"menu_order":0,"comment_status":"open","ping_status":"closed","template":"home.php","meta":{"footnotes":""},"class_list":["post-290","page","type-page","status-publish","has-post-thumbnail","hentry"],"psp_head":"<title>Activity Lifecycle With Example In Android - Tutorial, Code And Importance \u2013 Abhi Android<\/title>\r\n<meta name=\"description\" content=\"Complete tutorial on Activity Lifecycle with example explanation in Android. Activity is one of the building blocks of Android OS. In simple words Activity is a screen that user interact with\" \/>\r\n<meta name=\"robots\" content=\"index,follow\" \/>\r\n<link rel=\"canonical\" href=\"https:\/\/abhiandroid.com\/programming\/activity-life-cycle\" \/>\r\n","_links":{"self":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages\/290","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/comments?post=290"}],"version-history":[{"count":2,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages\/290\/revisions"}],"predecessor-version":[{"id":898,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages\/290\/revisions\/898"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/media\/309"}],"wp:attachment":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/media?parent=290"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}