Sunday, September 6, 2020

Activity Lifecycle in Android with Source code.

  • Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. 
  • The android Activity is the subclass of Context Theme Wrapper class.

Method

 

Description

onCreate

called when activity is first created.

 

onStart

 

called when activity is becoming visible to the user.

onResume

called when activity will start interacting with the user.

onPause

called when activity is not visible to the user.

onStop

called when activity is no longer visible to the user.

onRestart

called after your activity is stopped, prior to start.

onDestroy

called before the activity is destroyed.



EXAMPLE :-

activity_mail.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android Life Cycle Program!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>


MainActivity.java

package com.example.sunny.lifecycle;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Toast.makeText(getApplicationContext(),"onCreate Method Call",
Toast.LENGTH_LONG).show();

}

protected void onStart()
{
super.onStart();

Toast.makeText(getApplicationContext(),"onStart Method Call",
Toast.LENGTH_LONG).show();

}

@Override
protected void onRestart()
{
super.onRestart();
Toast.makeText(getApplicationContext(),"onRestart Method Call",
Toast.LENGTH_LONG).show();

}

protected void onPause()
{
super.onPause();
Toast.makeText(getApplicationContext(),"onPause Method Call",
Toast.LENGTH_LONG).show();

}

protected void onResume()
{
super.onResume();
Toast.makeText(getApplicationContext(),"onResume Method Call",
Toast.LENGTH_LONG).show();

}

protected void onStop()
{
super.onStop();

Toast.makeText(getApplicationContext(),"onStop Method Call",
Toast.LENGTH_LONG).show();

}

protected void onDestroy()
{
super.onDestroy();
Toast.makeText(getApplicationContext(),"onDestroy Method Call",
Toast.LENGTH_LONG).show();

}
}



OUTPUT




No comments:

Post a Comment

Please do not any spam link in Comment Box