Life Cycle in Android Development

In Android, the life cycle of an activity is controlled by 7 methods. Just like in Java the execution start with main() method, similarly in Android the execution starts with onCreate() method.

The 7 methods are as below:

  1. onCreate(): called when the activity is first created.
  2. onStart(): called when the activity is visible to the user.
  3. onResume(): called when the user starts interacting with the application.
  4. onPause(): called when user is not interacting with the activity and previous activity is being resumed.
  5. onStop(): called when the activity is no longer visible to the user.
  6. onRestart(): called when the activity restarts after stopping it.
  7. onDestroy(): called when the activity is destroyed by the system.

 


Example:

package com.pawanthepro.lifecycle;
package com.pawanthepro.lifecycle;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;

public class MainActivity extends Activity {

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Toast.makeText(getActivity(),"In onCreate() Method", Toast.LENGTH_SHORT).show();
   }

   /** Called when the activity is about to become visible. */
   @Override
   protected void onStart() {
      super.onStart();
      Toast.makeText(getActivity(),"In onStart() Method", Toast.LENGTH_SHORT).show();
   }

   /** Called when the activity has become visible. */
   @Override
   protected void onResume() {
      super.onResume();
      Toast.makeText(getActivity(),"In onResume() Method", Toast.LENGTH_SHORT).show();   
   }

   /** Called when another activity is taking focus. */
   @Override
   protected void onPause() {
      super.onPause();
      Toast.makeText(getActivity(),"In onPause() Method", Toast.LENGTH_SHORT).show();   
   }

   /** Called when the activity is no longer visible. */
   @Override
   protected void onStop() {
      super.onStop();
      Toast.makeText(getActivity(),"In onStop() Method", Toast.LENGTH_SHORT).show();   
   }

   /** Called just before the activity is destroyed. */
   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(getActivity(),"In onDestroy() Method", Toast.LENGTH_SHORT).show();
   }

}