Thursday 14 November 2013

Activity and its Lifecycle Methods

Each Screen in an Android Application is called an Activity.
If you want to build a screen, you need to extend and Activity in other words you need to write a class and
that should be a sub-class of Activity.

Before we go on to how we build a screen, we shall need to have some knowledge of how an activity works.

The Following are the Lifecycle methods of an activity.


1) onCreate
2) onStart
3) onRestart
4) onResume
5) onPause
6) onStop
7) onDestroy


OnCreate is called when the Activity is first created, Here is where in you shall load the UI you want to present to the user.
We shall look into how to build the UI in subsequent chapters.

When your Activity is partially visible or a Dialog is on top of your screen, that screen or Activity is in a paused state and onPause gets called.
When the dialog disappears or your activity becomes completely visible onResume is called.

If your Activity is completely hidden by another activity or your app is in the Background, the Activity shown in the app is a stopped state and onStop gets called.

An Activity is destroyed if the application is destroyed or the Android System destroys the Activity if it feels it is low on memory. In that case onDestroy is called.
You can do 'clean up' in onDestroy.


When An application is launched, the Main Activity(First Activity to be Shown) is called. The Sequence that it goes through is onCreate-->onStart-->onResume.


Note 1:
   When you create an Activity implementing the onCreate method is mandatory because you have to load the UI.
Implementing the rest of the methods is optional.

Note 2:
  When implementing methods like onPause, onResume, onStop, onDestroy, calling the super method is mandatory as follows:

public void onPause(){

super.onPause(); //This call to super is mandatory

}

public void onResume(){

super.onResume(); //This call to super is mandatory

}
If you do not call the super method the app crashes, that's the way it has been designed do not ask me.
So the Next chapter will be about building UIs that you shall be loading in onCreate







No comments:

Post a Comment