Android Activity Lifecycle With Example & Source Code


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.
Below is Activity Lifecycle Decription:--
onCreate() – Called when the activity is first createe
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
Android Activity Lifecycle Diagram
Generally, in android activity class uses different callback methods like onCreate(), onStart(), onPause(), onRestart(), onResume(), onStop() and onDestroy() to go through a different stages of activity life cycle
Following is the pictorial representation of Android Activity Life cycle which shows how Activity will behave in different stages using callback methods.
Android Activity Lifecycle Example:-
we  are going to create example of lifecycle :

MainActivity.java File Code
package com.example.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("Activity Lifecycle","onCreate invoked");
    }
    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Activity Lifecycle","onStart invoked");
    }
    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Activity Lifecycle","onResume invoked");
    }
    @Override
    protected void onPause() {
        super.onPause();
        Log.d("Activity Lifecycle","onPause invoked");
    }
    @Override
    protected void onStop() {
        super.onStop();
        Log.d("Activity Lifecycle","onStop invoked");
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("Activity Lifecycle","onRestart invoked");
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("Activity Lifecycle","onDestroy invoked");
    }
}


Post a Comment

0 Comments