Android- Activities

If you have previous knowledge about C, C++ or JAVA then you must have seen that the program starts from the  main() function. Similarly, android also initiates an Activity by calling its onCreate() function.

Activity has its own life cycle in which a sequence of callback methods run.

The below Activity life cycle diagram gives an overview of how the control flows in an activity.

basic-lifecycle

All the above functions are callbacks of Activity life cycle. However, all these callback functions are not necessarily be implemented in all your programs.

Knowing when each callback method is triggered and what is its role in an activity’s life cycle can surely help you write you code in the right callback function.

onCreate():

Called when the activity is first created. 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. Always followed by onStart().

onRestart():

Called after your activity has been stopped, prior to it being started again. Always followed by onStart()

onStart():

Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

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. Always followed by onPause().

onPause ():

Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A’s onPause() returns, so be sure to not do anything lengthy here.

onStop():

Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.

Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity’s process running after its onPause() method is called.

onDestroy():

The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() methods.

Knowing these callback methods better will help you understand the dynamics of Android even better as Activity is a fundamental part of App development. You can even check out Google’s official website for developers here.

Leave a Reply

Your email address will not be published. Required fields are marked *