Android Activity Lifecycle Example

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

1. Android Activity Back Stack.

android activity start new stack

Android use Task to manage activities, one task is a collection of some related activities which are stored in a stack.

Android activity can be stacked. The new started activity will be placed above the old one in the stack. When click the android device Back menu at bottom, the top activity in the stack will be destroyed, and the covered activity will be popped up and displayed again.

The stack name is Back Stack, it follows FILO ( First In Last Out ) principle.

android activity back stack 1

2. Android Activity State.

android activity state

Each activity will have four state in it’s life cycle.

  1. Running state : When an activity pop up to the top of the back stack, it’s in running state. Android OS will not recycle the activity in running state.
  2. 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 pause state. Only if the memory is very low, android system will take back the activity and release the resources.
  3. Stop state : When an activity is no longer on the top of the stack and is completely invisible, the activity goes into 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 takes back the stopped activity and frees up the resources.
  4. Destroy state : When an activity is removed from the back stack, it becomes destroy state. Android system will recycles this state of activity to ensure sufficient memory for the mobile phone.
READ :   Android Custom Content Provider Introduction

3. Android Activity State Related Methods.

For each android activity state, there is one related method that you can write code in it. You can do android application initialization when activity start, or do android app destruction or save activity info into text file before activity is destroyed.

android activity lifecycle methods

  1. onCreate() : This method is invoked when the activity is created for the first time. Commonly we can do some initialization work in this method.
  2. onDestroy() : This method is called before the activity is destroyed, and the state of the activity becomes destroyed.
  3. onStart() : This method is invoked when the activity become visible from invisible state.
  4. 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.
  5. 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.
  6. 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.
  7. 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.

android activity lifecycle example release

Main Layout Xml File.

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>

Main Activity Java File.

READ :   Android Sharedpreferences Save/Load Java Object Example

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.");
    }
}

Opened Normal Activity Layout Xml File.

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"/>

Opened Normal Activity Java File.

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.

This file includes constants string that is used as the log tag name. You can read article Android LogCat And Logging Best Practice for more detail about android log.

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";
}

Leave a Reply

Your email address will not be published. Required fields are marked *

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