App Activity Life Cycle In Android

In this article you will learn about app activity life cycles 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 an 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.

Activity has the following four different states.

  1. Activity does not exist.
  2. Activity is in foreground state.
  3. Activity is in background state.
  4. Activity is in paused state.

An activity has having seven major methods i.e.

  1. OnCreate
  2. OnStart
  3. OnResume
  4. OnPause
  5. OnStopped
  6. OnRestart
  7. OnDestroy

Let's talk abouteach one by one.

An 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 start.

Now if you press the back button of your smartphone then the current 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 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 call first? In C and C++ the main method is going to be call 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: