Thursday, March 14, 2013

Activity Life Cycle In Android

 Activity in Android :

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View).

An Activity represents   an UI with which a user can Interact.

Each activity in an application goes through its own lifecycle. Once and only once when
an activity is created, is the onCreate() function executed. If the activity exits, the
onDestroy() function is executed. In between, various events can lead to the activity
being in multiple different states, as illustrated in Figure .



As seen here, various common actions by the user can cause the activity to be paused,
killed, or even launch multiple versions of the application.


I have created an application which shows all the states of an Activity  and also attached the logs in which we can clearly see and understand about the life cycle of an Activity.


onCreate() :     Called when the activity is first created. This is first method called when an Activity  starts. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. generally in this method we write setContentView()  method and inflate the XML layout.

onStart(): Called when the activity is becoming visible to the user.

onResume():  Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.

onPause():  Called when when you start a New Activity , the previous Activity goes in Pause state and pushed in stack.  When we come back on previous  Activity , Previous Activty gets Poped from Stack and  onResume() method of previous Activity gets called.

onStop(): Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed.

onDestroy() : called when the  your activity is going to be destroyed.

The following Code/Example Illustrate all these things . You can copy the code and  run. I have displayed Toasts showing the states of Activity .

Here I have 2 Activities  1: DemoFirstActivity   2: Second Activity

Inside DemoFirstActivity  i have started Second Activity

We have two XML Layouts here  
main.xml  for  DemoFirstActivity
layout2.xml  for Second Activity


main.xml  :


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
>

  
     <TextView
         android:id="@+id/textView1"
         android:layout_gravity="center_horizontal"
         android:textSize="23dp"
         android:layout_marginTop="150dp"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="This Is Fist Activity Activity"
         />
  
    <Button
        android:id="@+id/button1"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="      Second Activity     "
        android:onClick="startSecondActivity"/>

</LinearLayout>




layout2.xml :


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
>

     <TextView
         android:id="@+id/textView1"
         android:layout_marginTop="150dp"
         android:layout_gravity="center_horizontal"
         android:textSize="23dp"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="This Is Second Activity" />

      </LinearLayout>

  

DemoFirstActivity.java



public class DemoFirstActivity extends Activity
{
    /** Called when the activity is first created. */


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Toast.makeText(this, "On Create Called In First Activity", Toast.LENGTH_LONG).show();
            Log.i("FirstActivity", "Inside onCreate");

           
    }
     
   
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        Toast.makeText(this, "On Start Called In First Activity", Toast.LENGTH_LONG).show();
        Log.i("FirstActivity", "Inside onStart")
;
    }
   
   
    @Override
    protected void onResume()
    {
        // TODO Auto-generated method stub
        super.onResume();
       
        Toast.makeText(this, "On Resume Called In First Activity", Toast.LENGTH_LONG).show();
        Log.i("FirstActivity", "Inside onResume");

    }
   
   
   
 @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        Toast.makeText(this, "On Pause Called In First Activity", Toast.LENGTH_LONG).show();
        Log.i("FirstActivity", "Inside onPause");

    }


   @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
       
        Toast.makeText(this, "On Stop Called In First Activity", Toast.LENGTH_LONG).show();
        Log.i("FirstActivity", "Inside onStop");

    }


   @Override
    protected void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();
        Toast.makeText(this, "On Destroy Called In First Activity", Toast.LENGTH_LONG).show();
        Log.i("FirstActivity", "Inside onDestroy");

       
    }
   
    public void startSecondActivity(View V)
    {
        // create an new Intent and Start Second Activity
        Intent intent=new Intent(this,SecondActivity.class);
        startActivity(intent);
    }
}
   
   

SecondActivity.java:



public class SecondActivity extends Activity
{
    /** Called when the activity is first created. */


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.layout2);
            Toast.makeText(this, "On Create Called In Second Activity", Toast.LENGTH_LONG).show();
            Log.i("SecondActivity", "Inside onCreate");
           
    }
     
   
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        Toast.makeText(this, "On Start Called In Second Activity", Toast.LENGTH_LONG).show();
        Log.i("SecondActivity", "Inside onStart");
    }
   
   
    @Override
    protected void onResume()
    {
        // TODO Auto-generated method stub
        super.onResume();
       
        Toast.makeText(this, "On Resume Called In Second Activity", Toast.LENGTH_LONG).show();
        Log.i("SecondActivity", "Inside onResume");
    }
   
   
   
 @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        Toast.makeText(this, "On Pause Called In Second Activity", Toast.LENGTH_LONG).show();
        Log.i("SecondActivity", "Inside onPause");
    }


   @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
       
        Toast.makeText(this, "On Stop Called In Second Activity", Toast.LENGTH_LONG).show();
        Log.i("SecondActivity", "Inside onStop");
    }


   @Override
    protected void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();
        Toast.makeText(this, "On Destroy Called In Second Activity", Toast.LENGTH_LONG).show();
        Log.i("SecondActivity", "Inside onDestroy");
       
    }
   
   
}



Logs:


03-14 15:33:31.313: I/FirstActivity(22609): Inside onCreate
03-14 15:33:31.318: I/FirstActivity(22609): Inside onStart
03-14 15:33:31.323: I/FirstActivity(22609): Inside onResume
03-14 15:33:44.183: I/FirstActivity(22609): Inside onPause
03-14 15:33:44.313: I/SecondActivity(22609): Inside onCreate
03-14 15:33:44.318: I/SecondActivity(22609): Inside onStart
03-14 15:33:44.323: I/SecondActivity(22609): Inside onResume
03-14 15:33:44.513: I/FirstActivity(22609): Inside onStop
03-14 15:34:03.578: I/SecondActivity(22609): Inside onPause
03-14 15:34:03.603: I/FirstActivity(22609): Inside onStart
03-14 15:34:03.603: I/FirstActivity(22609): Inside onResume
03-14 15:34:03.813: I/SecondActivity(22609): Inside onStop
03-14 15:34:03.818: I/SecondActivity(22609): Inside onDestroy


More Android Topics



Android : Introduction


       Eclipse Setup for Android Development

                     Configuring Eclipse for Android Development

          Begging With Android

                     Creating Your First Android Project
                     Understanding Android Manifest File of your android app


         Working With Layouts

                      Understanding Layouts in Android
                          Working with Linear Layout (With Example)
                                Nested Linear Layout (With Example)
                          Table Layout
                          Frame Layout(With Example)
                         Absolute Layout
                         Grid Layout


       Activity

                     Activity In Android
                     Activity Life Cycle
                     Starting Activity For Result
                     Sending Data from One Activity to Other in Android
                     Returning Result from Activity

     Working With Views

                     Using Buttons and EditText in Android 
                     Using CheckBoxes in Android 
                     Using AutoCompleteTextView in Android
                     Grid View

     Dialogs In Android

                     Working With Alert Dialog
                     Adding Radio Buttons In Dialog
                     Adding Check Boxes In Dialog
                     Creating Customized Dialogs in Android
                    Adding EditText in Dialog

                   Creating Dialog To Collect User Input

                 DatePicker and TimePickerDialog

                              Using TimePickerDialog and DatePickerDialog In android

    Working With SMS

                  How to Send SMS in Android
                  How To Receive SMS
                  Accessing Inbox In Android

    ListView:

               Populating ListView With DataBase

      Menus In Android

                    Creating Option Menu
                    Creating Context Menu In Android

      TelephonyManager

                    Using Telephony Manager In Android

     Working With Incoming Calls

                    How To Handle Incoming Calls in Android
                    How to Forward an Incoming Call In Android
                   CALL States In Android

    Miscellaneous

                   Notifications In Android
                   How To Vibrate The Android Phone
                   Sending Email In Android
                  Opening a webpage In Browser
                   How to Access PhoneBook In Android
                   Prompt User Input with an AlertDialog

   Storage:  Storing Data In Android


               Shared Prefferences  In Android

                             SharedPreferences In Android

               Files: File Handling In Android

                              Reading and Writing files to Internal Stoarage
                              Reading and Writing files to SD Card 
                         

                DataBase : Working With Database

                             Working With Database in Android
                             Creating Table In Android
                             Inserting, Deleting and Updating Records In Table in Android
                             How to Create DataBase in Android
                             Accessing Inbox In Android

     Animation In Android:

                  Animating A Button In Android

12 comments:

  1. thanks it is very useful for me present in my college days

    ReplyDelete
  2. NannetteS fotballdrakter SwenFelde
    DamonScha Fodboldtrojer Born Rustypata
    Catherine fotbollstr�jor barn PearlineW
    Audreavbo Billige Fodboldtrojer CaitlinSm
    HopeTunbr maglie del calcio Terrellyj

    ReplyDelete
  3. online casino real money
    online casino gambling
    casino games real money
    casinos online
    casino games

    ReplyDelete
  4. However, the darkness from the show, along with many adult themes littered
    through the entire storyline, get this to inappropriate fare for young children.
    And it will increase the shutter speed hence the photo isn't overexposed through the extra
    light allowed together with the more expensive aperture.
    You can either choose a website that allows you to watch the episodes totally free or access a paid software in order to transform your own PC in a fully functioning television.

    ReplyDelete
  5. http://www.micropromocodes.com Best Place for Upto 80% Off Free Coupon Codes, Promotion Codes,
    Discount Deals and Promo Offers For Online Shopping,Upto 80% Off Promo Coupon Codes.
    Save on Online Shopping Always. Use Coupons.
    Exclusive Coupons · Genuine Offers · Updated Daily · Best Coupons
    · Free Coupons · Best Offers,
    Types: Coupon Codes, Discount Coupons, Offers & Deals,Save Upto 80% Off on Microsoft Store Promo Code,

    ReplyDelete
  6. What's Going down i'm new to this, I stumbled upon this I've found
    It absolutely useful and it has aided me out loads.
    I'm hoping to contribute & help different customers like its
    helped me. Great job.

    ReplyDelete
  7. I don't even know how I ended up here, but I thought this post was good.
    I do not know who you are but certainly you're
    going to a famous blogger if you are not already ;) Cheers!

    ReplyDelete
  8. Thanks for some other informative website. Where else could I am getting that type of information written in such an ideal
    method? I've a challenge that I'm just now running on, and I've been on the look out for
    such information.

    ReplyDelete
  9. Oh my goodness! Impressive article dude! Thank you, However I am encountering
    difficulties with your RSS. I don't know the reason why I can't join it.
    Is there anybody getting the same RSS problems?
    Anyone who knows the solution will you kindly respond? Thanks!!

    ReplyDelete
  10. Highly energetic blog, I enjoyed that a lot. Will there be a part 2?

    ReplyDelete
  11. nyfw nyfw2019 Magical fashion show by an amazing artist @PenarandaWorld @ Baccarat Hotel
    New York …

    ReplyDelete
  12. What i do not realize is if truth be told how you're no longer
    really a lot more well-liked than you might be now. You are so intelligent.
    You already know thus considerably with regards to this subject, made me in my opinion believe it from so
    many numerous angles. Its like men and women aren't involved except it's one thing to accomplish
    with Girl gaga! Your individual stuffs excellent. At all times maintain it up!

    ReplyDelete