Java Andorid Program to Demonstrate Activity Life Cycle

Here is source code of the Program to Demonstrate Activity Life Cycle in Android. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.


An Activity in android application can take these states
1.Created – Activity is created
2.Running – Activity is visible and interacts with the user
3.Paused -Activity is still visible but partially obscured, instance is running but might be killed by the system.
4.Stopped – Activity is not visible, instance is running but might be killed by the system.
5.Destroyed -Activity has been terminated by the system of by a call to its finish() method.
When an activity is first created its onCreate() method gets called then if the subsequent onStart() method gets called and then the activity proceeds to its onResume() method it here where the activity starts to run , now another activity can come into foreground which forces this app to go into a paused state , now either this activity can g
et killed by the os or get resumed or the activity calls its onStop() method where the activity now goes into its Ondestroy() method and get killed.
For more info go to – http://developer.android.com/training/basics/activity-lifecycle/starting.html

The following code demonstartes the above procedure.
========================================================================
Main Activity

package com.example.activity_life;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        notify("onCreate");
    }

    @Override
    protected void onPause() {
        super.onPause();
        notify("onPause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        notify("onResume");
    }

    @Override
    protected void onStop() {
        super.onStop();
        notify("onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        notify("onDestroy");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        notify("onRestoreInstanceState");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        notify("onSaveInstanceState");
    }

    private void notify(String methodName) {
        String name = this.getClass().getName();
        String[] strings = name.split("\\.");
        Toast.makeText(getApplicationContext(),
                methodName + "" + strings[strings.length - 1],
                Toast.LENGTH_LONG).show();
    }

}

========================================================================