Ticker

10/recent/ticker-posts

Header Ads Widget

Android Activity Lifecycle

 Activity lifecycle

Android activities have a defined lifecycle to manage application runtime from launch to the end of application life. The Activity base class defines a series of events that govern the life cycle of an activity.



 Activities

An Android activity represents a screen with which a user can interact. The Activity class is used to respond to user input. An activity can transition to another activity as the user navigates between screens. Any component that is drawn to the screen lives within the bounds of an activity but Activity class itself does not draw anything. A Java source file represents an activity class in app/java/

Official diagram explaining the activity lifecycle from :

https://developer.android.com/reference/android/app/Activity.html.

The Activity class defines the following events:

onCreate() : Called when the activity is first created. This is a place where we usually do main UI elements initialization.

onStart() : Called when the activity becomes visible to the user

onResume() : Called when the activity starts interacting with the user. At this stage we can start any services or code that needs to run while your activity is in the foreground.

onPause() : Called when the current activity is being paused and the previous activity is being resumed. This is a good place to save all the information you will need when you resume again. If there are any unsaved changes, you should save them here. At this stage we can stop any services or code that does not need to run when your activity is not in the foreground.

onStop() : Called when the activity is no longer visible to the user

onDestroy() : Called before the activity is destroyed by the system. At this stage we should free up resources before the activity is destroyed.

onRestart() : Called when the activity has been stopped and is restarting again. For example, you turn off your phone screen (lock it) and then unlock it again.

 

Conclusion

1.       When an activity is created for the first time, the onCreate() method is called.

2.  When an activity is started, the onStart() and onResume() methods are always called, regardless of whether the activity is restored from the background or newly created.

3.      The onPause() method is called when an activity is sent to the background or when a user kills an activity by tapping the Back button

4.  An activity is destroyed when we click the Back button. It is important to understand that whatever state the activity is currently in will be lost. So you need to write some logic in your activity to preserve its state when the activity is destroyed