Translate

Monday, 14 March 2016

Android Activity Lifecycle 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
  1. package com.example.activitylifecycle;  
  2. import android.os.Bundle;  
  3. import android.app.Activity;  
  4. import android.util.Log;  
  5. import android.view.Menu;  
  6. public class MainActivity extends Activity {  
  7.     @Override  
  8.     protected void onCreate(Bundle savedInstanceState) {  
  9.         super.onCreate(savedInstanceState);  
  10.         setContentView(R.layout.activity_main);  
  11.         Log.d("lifecycle","onCreate invoked");  
  12.     }  
  13.     @Override  
  14.     protected void onStart() {  
  15.         super.onStart();  
  16.          Log.d("lifecycle","onStart invoked");  
  17.     }  
  18.     @Override  
  19.     protected void onResume() {  
  20.         super.onResume();  
  21.          Log.d("lifecycle","onResume invoked");  
  22.     }  
  23.     @Override  
  24.     protected void onPause() {  
  25.         super.onPause();  
  26.          Log.d("lifecycle","onPause invoked");  
  27.     }  
  28.     @Override  
  29.     protected void onStop() {  
  30.         super.onStop();  
  31.          Log.d("lifecycle","onStop invoked");  
  32.     }  
  33.        @Override  
  34.     protected void onRestart() {  
  35.         super.onRestart();  
  36.          Log.d("lifecycle","onRestart invoked");  
  37.     }     
  38.     @Override  
  39.     protected void onDestroy() {  
  40.         super.onDestroy();  
  41.          Log.d("lifecycle","onDestroy invoked");  
  42.     }  
  43. }  


Output:

You will not see any output on the emulator or device. You need to open logcat.
android activity life cycle example output 1
Now see on the logcat: onCreate, onStart and onResume methods are invoked.
android activity life cycle example output 2

No comments:

Post a Comment