Wednesday, April 3, 2013

Android Activity Life Cycle



An activity is a user interaction screen that the user use the device at one time. An application can have multiple activities , and the user go back and among them. That's why activities are the most visible part of our application.

I usually use a website as an analogy for activities. Just like a website consists of multiple pages, so does an Android application consist of multiple activities. Just like a website has a “home page,” an Android app has a “main” activity, usually the one that is shown first when you launch the application. And just like a website has to provide some sort of navigation among various pages, an Android app should do the same.

for example: on the website, we can navigate from a page on one website to a page on another. Similarly, in Android, we look at an activity of an application, and navigate to another activity of an application in a completely separate application. For example, if you are in your Contacts app and you choose to text a friend, you’d be launching the activity to compose a text message in the Messaging application.

Launching an activity can be quite expensive. It may involve creating a new Linux process, allocating memory for all the UI objects, inflating all the objects from XML layouts, and setting up the whole screen. Since we’re doing a lot of work to launch an activity, it would be a waste to just toss it out once the user leaves that screen. To avoid this waste, the activity life cycle is managed via Activity Manager.

Activity Manager is responsible for creating, destroying, and managing activities. For example, when the user starts an application for the first time, the Activity Manager will create its activity and put it onto the screen. Later, when the user switches screens, the Activity Manager will move that previous activity to a holding place. This way, if the user wants to go back to an older activity, it can be started more quickly. Older activities that the user hasn’t used in a while will be destroyed in order to free more space for the currently active one. This mechanism is designed to help improve the speed of the user interface and thus improve the overall user experience.

Programming for Android is conceptually different than programming for some other environments. In Android, you find yourself responding more to certain changes in the state of your application rather than driving that change yourself. It is a managed, container-based environment similar to programming for Java applets or servlets. So, when it comes to an activity life cycle, you don’t get to say what state the activity is in, but you have plenty of opportunity to say what happens during the transitions from state to state. Figure 4-1 shows the states that an activity can go through.


Android operating system  have Java classes that  extended it's predefined classes with different method. Activity is also a predefined class that have predefined method. All method run sequentially by nature of life cycle . Activity is a class that represent UI part in android.  it have some sequential flow as per different conditions.

An activity is a user interaction screen that the user use the device at one time. An application can have multiple activities , and the user go back and among them. That's why activities are the most visible part of our application.

I usually use a website as an analogy for activities. Just like a website consists of multiple pages, so does an Android application consist of multiple activities. Just like a website has a “home page,” an Android app has a “main” activity, usually the one that is shown first when you launch the application. And just like a website has to provide some sort of navigation among various pages, an Android app should do the same.

for example: on the website, we can navigate from a page on one website to a page on another. Similarly, in Android, we look at an activity of an application, and navigate to another activity of an application in a completely separate application. For example, if you are in your Contacts app and you choose to text a friend, you’d be launching the activity to compose a text message in the Messaging application.

Launching an activity can be quite expensive. It may involve creating a new Linux process, allocating memory for all the UI objects, inflating all the objects from XML layouts, and setting up the whole screen. Since we’re doing a lot of work to launch an activity, it would be a waste to just toss it out once the user leaves that screen. To avoid this waste, the activity life cycle is managed via Activity Manager.

Activity Manager is responsible for creating, destroying, and managing activities. For example, when the user starts an application for the first time, the Activity Manager will create its activity and put it onto the screen. Later, when the user switches screens, the Activity Manager will move that previous activity to a holding place. This way, if the user wants to go back to an older activity, it can be started more quickly. Older activities that the user hasn’t used in a while will be destroyed in order to free more space for the currently active one. This mechanism is designed to help improve the speed of the user interface and thus improve the overall user experience.





 For Activity We have to know first  What is an Activity?

An activity is a user interaction screen that the user use the device at one time. An application can have multiple activities , and the user go back and among them. That's why activities are the most visible part of our application.
Activity represents the view part of android with the use of different methods to show and upload the user interface.


 android activity life cycle method sequence are below:


                                               1:-  onCreate();
                                               
                                               2:- onStart();    or   onRestart();
                                               
                                               3:- onResume();

                                               4:- onPause();

                                               5:- onStop();

                                               6:- onDestroy();


1:- onCreate():-


When an activity doesn’t exist in memory, it is in a starting state. While it’s starting up, the activity will go through a whole set of callback methods that you as a developer have an opportunity to fill out. Eventually, the activity will be in a running state.

Keep in mind that this transition from starting state to running state is one of the most expensive operations in terms of computing time, and this also directly affects the battery life of the device. This is the exact reason why we don’t automatically destroy activities that are no longer shown. The user might want to come back to them, so we keep them around for a while.



In Android Activity Life Cycle, this method Called when the activity is first created. Android first method of life cycle is onCreate(), it has parameter Bundle type named as savedInstanceState. that contains bundle information send by previous activity. it will register all the views and bind data to lists.

2:- onRestart():-

The activity in a running state is the one that is currently on the screen and interacting with the user. We also say this activity is in focus, meaning that all user interactions—such as typing, touching the screen, and clicking buttons—are handled by this one activity. As such, there is only one running activity at any given time.

The running activity is the one that has priority in terms of getting the memory and resources it needs to run as quickly as possible. This is because Android wants to make sure the running activity is zippy and responsive to the user.


In Android Activity Life Cycle, this method called after your activity has been stopped,  it being started again. Always followed by onStart().
 
2:- onStart():-  In Android Activity Life Cycle, this method Android Acitvity now starting all Views to visualisation state for all the Views. and it will now proceed to onResume() Method.

3:- onResume():-In Android Activity Life Cycle, this method is called With in this state Activity goes in  foreground and the user can interact with it.


4:- onPause():-  When an activity is not in focus (i.e., not interacting with the user) but still visible on the screen, we say it’s in a paused state. This is not a typical scenario, because the device’s screen is usually small, and an activity is either taking up the whole screen or none at all. We often see this case with dialog boxes that come up in front of an activity, causing it to become Paused. All activities go through a paused state en route to being stopped.

Paused activities still have high priority in terms of getting memory and other resources. This is because they are visible and cannot be removed from the screen without making it look very strange to the user.


In Android Activity Life Cycle, this method called When user call another activity by present activity then it will goes onPause() State.
it will be onPause() state untill it shows up.

5:- onStop():-  When an activity is not visible, but still in memory, we say it’s in a stopped state. Stopped activity could be brought back to the front to become a Running activity again. Or, it could be destroyed and removed from memory.

The system keeps activities around in a stopped state because it is likely that the user will still want to get back to those activities some time soon, and restarting a stopped activity is far cheaper than starting an activity from scratch. That is because we already have all the objects loaded in memory and simply have to bring it all up to the foreground.

Stopped activities can be removed from memory at any point.


In Android Activity Life Cycle, this method is called When activity No Longer Visible and not called then the activtiy goes onStop() State.
we will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.

6:- onDestroy():- A destroyed activity is no longer in memory. The Activity Manager decided that this activity is no longer needed and has removed it. Before the activity is destroyed, it can perform certain actions, such as save any unsaved information. However, there’s no guarantee that your activity will be stopped prior to being destroyed. It is possible for a paused activity to be destroyed as well. For that reason, it is better to do important work, such as saving unsaved data, en route to a paused state rather than a destroyed state.
In Android Activity Life Cycle, this method called Activty goes destroy State when it will got any error or get closed. this can also be happed when the system is temporarily destroying this instance of the activity to save space.



When Activity first Time load below methods called:-

----> onCreate()
----> onStart()
----> onResume()
 
When We go to another Activity Then below Methods Called.
 
---> onPause()
---> onStop() 
When returning from Second Activity to First Acitvity then below Methods Called.

---> onRestart()
---> onStart()
---> onResume()
 
When we exit from Application these methods Called
 
---> onPause()
---> onStop()
---> onDestroy() 





Activity Life Cycle  sequence are below: --



Image
for more detail go to http://developer.android.com/training/basics/activity-lifecycle/index








Example for Activity Life Cycle:------------



package com.android.demo;

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

public class ActivityA exends  Activity{
   
    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        Toast.makeText(this, "create", 2000).show();
Button btn  =(Button)findViewById(R.id.btn);
        btn.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent  = new Intent(this, AcitivityB.class);
                startActivity(intent);
            }
        });
       
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        Toast.makeText(this, "start", 2000).show();

    }
   
    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
        Toast.makeText(this, "restart", 2000).show();

    }
   
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Toast.makeText(this, "resume", 2000).show();

    }
   
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        Toast.makeText(this, "pause", 2000).show();

    }
   
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        Toast.makeText(this, "pause", 2000).show();

    }
   
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Toast.makeText(this, "destroy", 2000).show();

    }
   
}


/////////////////////////////////  Activity B//////////////////////////////////////////////

package com.android.demo;

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

public class ActivityB exends  Activity{
   
      @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        Toast.makeText(this, "create", 2000).show();

       
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        Toast.makeText(this, "start", 2000).show();

    }
   
    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
        Toast.makeText(this, "restart", 2000).show();

    }
   
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Toast.makeText(this, "resume", 2000).show();

    }
   
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        Toast.makeText(this, "pause", 2000).show();

    }
   
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        Toast.makeText(this, "pause", 2000).show();

    }
   
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Toast.makeText(this, "destroy", 2000).show();

    }
   
}

6 comments: