Search This Blog

Wednesday 13 June 2012

Sample Code - Activity Life Cycle



Android Sample - ActivitySample: ActivitySample is an android sample for explaining the android activity life cycle.
Step 1 : Create a android project in eclipse with any name or “ActivitySample”.
Once the sample created explore the project src and open the activity class


The main activity class is generated by wizard for the application. Add the highlighted code.

package com.creativeandroidapps.SampleActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class ActivitySampleActivity extends Activity {
    /** Called when the activity is first created. */
    private static final String TAG = "MainActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.i(TAG, "Activity Life Cycle : onCreate : Activity Created");
    }
}


Now add the following life cycle methods


@Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG,"Activity Life Cycle : onStart : Activity Started");
        
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG,"Activity Life Cycle : onResume : Activity Resumed");
    }
    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG,"Activity Life Cycle : onPause : Activity Paused");
    }
    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG,"Activity Life Cycle : onStop : Activity Stoped");
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG,"Activity Life Cycle : onDestroy : Activity Destroyed");
    }


Now right click project and Run the sample in emulator and check the log in logcat to see the android activity life cycle.


logcat
Android Life Cycle in logcat





































No comments:

Post a Comment