Search This Blog

Tuesday 12 June 2012

Tutorial - Activity Life Cycle (Android)



What is Activity ? - Activity is an application component provides the screen to interact with user on the device. Activity class provides the methods to create and manage the windows on the screen.

Activity Life Cycle

An android application consist a set of multiple activities. An activity in android application provides the user interface or object to interact with the device. One of the activities of the application is the main activity. Each activity has its own lifecycle and an activity can start another activity to perform some actions and is able to create a chain of activities.

Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack"). When a new activity starts, it is pushed onto the back stack and takes user focus. The back stack abides to the basic "last in, first out" stack mechanism, so, when the user is done with the current activity and presses the Back button, it is popped from the stack (and destroyed) and the previous activity resumes.

The activity in the application will implement by extending the class by Activity class. The activity life cycle is processed by callback methods.

The following are the callback methods need to implement to handle the activity lifecycle.


public class CreativeActivity extends Activity {
   
@Override
   
public void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
       
// The activity is being created.
        //here we can do the – UI initialization, Background threads
      }
   
@Override
   
protected void onStart() {
       
super.onStart();
       
// The activity is about to become visible.
   
}
   
@Override
   
protected void onResume() {
       
super.onResume();
       
// The activity has become visible (it is now "resumed").
   
}
   
@Override
   
protected void onPause() {
       
super.onPause();
       
// Another activity is taking focus (this activity is about to be "paused").
   
}
   
@Override
   
protected void onStop() {
       
super.onStop();
       
// The activity is no longer visible (it is now "stopped")
   
}
   
@Override
   
protected void onDestroy() {
       
super.onDestroy();
       
// The activity is about to be destroyed.
   
}
}

No comments:

Post a Comment