Activity Lifecycle:
The life of an activity is represented or controlled by 7 methods of Activity class.
1) onCreate
2) onStart
3) onResume
4) onPause
5) onStop
6) on Restart
7) onDestroy
onCreate: Called when Activity is first created
onStart: Called when Activity is becoming visible to the user
onResume: Called when Activity is visible and user starts interacting
onPause: Called when Activity is about to be invisible
onStop: Called when Activity is no longer visible to the user
onRestart: Called when Activity is stopped, prior to start
onDestroy: Called before the Activity is destroyed
Example for on Restart method:
If we move from activity-1 to activity-2 without destroying the activity-1, whenever we come back to activity-1 from activity-2, onRestart method will be called in activity-1. In this case, onCreate will not be called in activity-1. onCreate will be called only if the activity is destroyed means onDestroy is called.
Create an Android application describes Lifecycle of the Activity
XML:
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:gravity=”center”
android:orientation=”vertical”>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Activity Lifecycle”
android:textSize=”25sp”
android:textStyle=”bold” />
</LinearLayout>
Activity class:
public class DemoActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo1);
Log.i(“Activity Lifecycle”, “onCreate method called”);
}
@Override
protected void onStart() {
super.onStart();
Log.i(“Activity Lifecycle”, “onStart method called”);
}
@Override
protected void onResume() {
super.onResume();
Log.i(“Activity Lifecycle”, “onResume method called”);
}
@Override
protected void onPause() {
super.onPause();
Log.i(“Activity Lifecycle”, “onPause method called”);
}
@Override
protected void onStop() {
super.onStop();
Log.i(“Activity Lifecycle”, “onStop method called”);
}
@Override
protected void onRestart() {
super.onRestart();
Log.i(“Activity Lifecycle”, “onRestart method called”);
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(“Activity Lifecycle”, “onDestroy method called”);
}
}
AndroidManifest.xml:
Register the above activity in AndroidManifest.xml inside <application> tag as follows
<activity android:name=”.DemoActivity”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>