Android Activity Lifecycle Example

Android activity life cycle is very important. You can make your android application more efficient and smooth when you understand the activity life cycle clearly. This article will introduce the android activity life cycle to you with examples.

1. Android Activity Back Stack.

  1. Android uses Task to manage activities, one task is a collection of some related activities which are stored in a stack.
    android-activity-start-new-stack
  2. Android activity can be stacked. The newly started activity will be placed above the old one in the stack.
  3. When clicking the android device Back menu at the screen bottom, the top activity in the stack will be destroyed, and the covered activity will be popped up and be displayed again.
  4. The stack name is Back Stack, it follows FILO ( First In Last Out ) principle.
    android-activity-back-stack-1

 

2. Android Activity State.

  1. Each activity will have four states in it’s life cycle.
    android-activity-state
  2. Running state: When an activity pops up to the top of the back stack, it’s in running state. Android OS will not recycle the activity in the running state.
  3. Pause state: When an activity is no longer on the top of the stack, but still visible (the activity on the top of the stack doesn’t cover the entire screen), the activity goes into the pause state. Only if the memory is very low, the android system will take back the activity and release the resources.
  4. Stop state: When an activity is no longer on the top of the stack and is completely invisible, the activity goes into the stop state. Android system will still save the corresponding state and member variables for this activity, but when memory is needed elsewhere, the system will take back the stopped activity and frees up the resources.
  5. Destroy state: When an activity is removed from the back stack, it comes to the destroy state. Android system will recycle this state of activity to ensure sufficient memory for the mobile phone.

3. Android Activity State Related Methods.

  1. For each android activity state, there is one related method that you can write code in it.
  2. You can do android application initialization when an activity starts, or do android app destruction, or save activity info into a text file before the activity is destroyed.
    android-activity-lifecycle-methods
  3. onCreate(): This method is invoked when the activity is created for the first time. Commonly we can do some initialization work in this method.
  4. onDestroy(): This method is called before the activity is destroyed, and the state of the activity becomes destroyed.
  5. onStart(): This method is invoked when the activity becomes visible from the invisible state.
  6. onStop(): This method is called when the activity is completely invisible. The main difference between this and the onPause() method is that if the new activity started is a dialog style activity, the onPause() method is executed and the onStop() method is not executed.
  7. onPause(): This method is called when the system is ready to start or reply to another activity. We usually release some CPU resources in this method and save some key data. However, this method must be run quickly, or it will affect the use of other stack top activities.
  8. onResume(): This method is called when the activity is ready to interact with the user, and the activity must be at the top of the stack and running.
  9. onRestart(): This method is called before the activity changes from the stop state to the running state, which means that the activity is restarted.

4. Android Activity Method Demo.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/Fji9Dzf-GUw

4.1 Main Layout Xml File.

  1. activity_life_cycle.xml
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <Button
            android:id="@+id/startNormalActivityButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Start Another Activity"/>
    
    </LinearLayout>

4.2 Main Activity Java File.

  1. ActivityLifeCycleActivity.java
    package com.dev2qa.example;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    
    import com.dev2qa.example.constant.LogTagName;
    
    public class ActivityLifeCycleActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            Log.d(LogTagName.LOG_TAG_UI, "Main activity create.");
    
            setContentView(R.layout.activity_life_cycle);
    
            setTitle("dev2qa.com - Activity Lifecycle Example");
    
            Button startNormalActivityButton = (Button)findViewById(R.id.startNormalActivityButton);
            startNormalActivityButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(ActivityLifeCycleActivity.this, ActivityLifeCycleNormalActivity.class);
                    startActivity(intent);
                }
            });
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            Log.d(LogTagName.LOG_TAG_UI, "Main activity start.");
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            Log.d(LogTagName.LOG_TAG_UI, "Main activity stop.");
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            Log.d(LogTagName.LOG_TAG_UI, "Main activity destroy.");
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            Log.d(LogTagName.LOG_TAG_UI, "Main activity pause.");
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            Log.d(LogTagName.LOG_TAG_UI, "Main activity resume.");
        }
    
        @Override
        protected void onRestart() {
            super.onRestart();
            Log.d(LogTagName.LOG_TAG_UI, "Main activity restart.");
        }
    }

4.3 Opened Normal Activity Layout Xml File.

  1. activity_life_cycle_normal.xml
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="This is the normal activity."
        android:textSize="20dp"/>

4.4 Opened Normal Activity Java File.

  1. ActivityLifeCycleNormalActivity.java
    package com.dev2qa.example;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    
    import com.dev2qa.example.constant.LogTagName;
    
    public class ActivityLifeCycleNormalActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            Log.d(LogTagName.LOG_TAG_UI, "Normal activity create.");
    
            setContentView(R.layout.activity_life_cycle_normal);
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            Log.d(LogTagName.LOG_TAG_UI, "Normal activity start.");
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            Log.d(LogTagName.LOG_TAG_UI, "Normal activity stop.");
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            Log.d(LogTagName.LOG_TAG_UI, "Normal activity destroy.");
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            Log.d(LogTagName.LOG_TAG_UI, "Normal activity pause.");
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            Log.d(LogTagName.LOG_TAG_UI, "Normal activity resume.");
        }
    
        @Override
        protected void onRestart() {
            super.onRestart();
            Log.d(LogTagName.LOG_TAG_UI, "Normal activity restart.");
        }
    
    }

5. Log Tag Name Constant Java File.

  1. This file includes some constants strings that are used as the log tag name. You can read the article Android LogCat And Logging Best Practice for more detail about android logs.
  2. LogTagName.java
    package com.dev2qa.example.constant;
    
    public class LogTagName {
    
        public static final String  LOG_TAG_UI = "LOG_TAG_UI";
    
        public static final String  LOG_TAG_NETWORK = "LOG_TAG_NETWORK";
    
        public static final String  LOG_TAG_DATABASE = "LOG_TAG_DATABASE";
    
        public static final String  LOG_TAG_LOGIC = "LOG_TAG_LOGIC";
    
        public static final String  LOG_TAG_APP = "LOG_TAG_APP";
    }
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x