Android Life Cycle of Activity

Android Tutorial - Javatpoint



Basics of Android


Android Life Cycle of Activity

We can control and manage the resource through the life cycle methods of activity.
There are 7 life cycle methods of android.app.Activity class. They are as follows:

MethodDescription
onCreatecalled when activity is first created.
onStartcalled when activity is becoming visible to the user.
onResumecalled when activity will start interacting with the user.
onPausecalled when activity is not visible to the user.
onStopcalled when activity is no longer visible to the user.
onRestartcalled after your activity is stopped, prior to start.
onDestroycalled before the activity is destroyed.

Android Activity Life Cycle Example





It provides the details about the invocation of life cycle methods of activity. In this example, we are displaying the content on the logcat.
File: MainActivity.java
package com.example.activitylifecycle;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("lifecycle","onCreate invoked");
    }
    @Override
 protected void onStart() {
  super.onStart();
   Log.d("lifecycle","onStart invoked");
 }
    @Override
 protected void onResume() {
  
  super.onResume();
   Log.d("lifecycle","onResume invoked");
 }
 

 @Override
 protected void onPause() {
  
  super.onPause();
   Log.d("lifecycle","onPause invoked");
 }
 @Override
 protected void onStop() {
  
  super.onStop();
   Log.d("lifecycle","onStop invoked");
 }
 
       @Override
 protected void onRestart() {
  
  super.onRestart();
   Log.d("lifecycle","onRestart invoked");
 } 
 @Override
 protected void onDestroy() {
  
  super.onDestroy();
   Log.d("lifecycle","onDestroy invoked");
 }
}



Output:

You will not see any output on the emulator or device. You need to open logcat.



Now see on the logcat: onCreate, onStart and onResume methods are invoked.



Now click on the HOME Button. You will see onPause method is invoked.




After a while, you will see onStop method is invoked.



Now see on the emulator. It is on the home. Now click on the center button to launch the app again.



Now click on the lifecycleactivity icon.



Now see on the logcat: onRestart, onStart and onResume methods are invoked.



If you see the emulator, application is started again.

Now click on the back button. Now you will see onPause methods is invoked.

After a while, you will see onStop and onDestroy methods are invoked.



onCreate and onDestroy methods are called only once throughout the lifecycle.




PREVIOUS                                                                        NEXT

No comments:

Post a Comment

Don't be a self fish share with your friends