App Activity Life Cycle In Android

What is an Activity?

 
An activity in Android is a single screen in the application with some UI components. It’s a Java file.
 

How do we create an activity?

 
The first step to create activity is to create a class which is a subtype of android.app.Activity, or, put simply, it extends the activity class in your Java class.
 

Why do we need to extend this activity class?

 
To understand this question you must first understand the lifecycle of an activity.
 
The activity has the following four different states.
  1. The activity does not exist.
  2. Activity is in the foreground state.
  3. Activity is in the background state.
  4. Activity is in the paused state.
An activity has to have seven major methods i.e.
  1. OnCreate
  2. OnStart
  3. OnResume
  4. OnPause
  5. OnStopped
  6. OnRestart
  7. OnDestroy
Let's talk about each one by one.
 
The activity comes from does not exist to foreground state by calling three different states:
  • OnCreate
  • OnStart
  • OnResume
However, if your application has some login page and when you click on this login button suddenly another activity comes into the foreground state,  the previous activity now goes to the background state by calling two methods.
  • OnPause
  • OnStop
When your activity is in the foreground state and you suddenly hit the power button or you getting some incoming call then your activity doesn't get destroyed. Meanwhile, your activity goes into the paused state by calling the OnPause method. And once you hit the power button again or you're done with the incoming call, then once again your activity comes into the foreground state by calling OnResume method.
 
Remember that all the screens are going to maintain in the start.
 
Now if you press the back button of your smartphone then the currently visible activity is going to be destroyed and the background activity is going into the foreground state.
 
Once you press the back button the activity goes from the foreground state to the destroying state by calling the OnPause, OnStopped, and OnDestroy method. Meanwhile, when you press the back button the background activity goes to the foreground state by calling OnCreate OnRestart and OnResume states
 
Now the question is, who can manage all of these things?
 
You don't need to manage all of these things. Create one class witha subtype of android.app.Activity.
 
So which method is going to be called first? In C and C++ the main method is going to be called Zfirst but here, the OnCreate method is going to start first. The execution starts with OnCreate.
 
Design the XML file and set the content view of your XML file to the Java file by using setContentView (R.layout.yourxmlfilename).
 
 
Read more articles on Android


Similar Articles