An Activity is an application component that provides a screen with which users can interact in order to do something.
Activity Life Cycle Methods:
Life cycle methods will be called by the android OS. So in each life cycle method we must call super class method.
onCreate: This method calls by the android os whenever the activity is launched.
In this method we write code for create view hierarchy. It draw the UI on the screen.
For draw the UI on the screen we need to call a method of View class.
Here activity_main is layout xml file in which we define the UI elements.
For every Resource which we keep in the res folder a hex reference will be created
in R.java class. Using which we can access the resources in the source code.
onStart: Whenever activity is launched Android OS will call 3 callback methods
in a sequential those are onCreate and onStart and onResume. In onStart we need
to write code which needs to be executed after immediately UI is loaded. like
start service or register broadcast receiver etc.
onResume: Whenever this callback methods is calling android OS that means user able
see the UI and can perform the operations.
onPause: This method is called user can able to see the UI partially and can’t perform any operation. When user receive a dialog this method is called. In this method we need to write code for save user data. i.e write important data in the database. This operation should be light weight.
onStop: This method is called when the user leave the activity. When user move from 1 activity to other activity this method will be called in the last. So in this method we need to write code related to release the resource like close database connection and close http connections. stop services which trigger by this activity if it is not required to run and also we can unregister the broadcast receiver.
onDestroy: This method is called by Android OS when the activity is no longer exist.
This method is called when the user click back button.
onRestart: When user moves from one activity to another activity and press back
button to come last activity or whenever user press the home screen and relaunched
activity from the menu.
Other call back methods which used for the save the state of an activity.
- onSavedInstanceState: This is called after onPause callback method called. Here we can write the code for save the state of variables which need to be restored when user comes back to the activity. We need to use this method for the values which are temporary(When application destroys values will be destroyed).
- onRestoreInstanceState: This is called after onCreate call back method, In this method this method receive the saveInstance state. In this method we can restore the values which are saved in the onSavedInstanceState callback method.