- Android Activity Lifecycle
- What is an Activity in Android?
- What is the Activity Lifecycle?
- Real example use-cases of Activity Lifecycle
- Activity in Android
- What is an Activity in Android?
- Different States of App (or, the main App Activity)
- Active State
- Paused State
- Stopped State
- Destroyed State
- Activity Lifecycle methods
- Памятка по жизненному циклу Android — часть I. Отдельные Activity
- Часть 1: Activity
- Одно Aсtivity — Сценарий 1. Приложение завершено и перезапущено
- Одно Aсtivity — Сценарий 2. Пользователь уходит
- Одно Aсtivity — Сценарий 3. Изменение кофигурации
- Одно Aсtivity — Сценарий 4. Приложение приостановлено системой
Android Activity Lifecycle
Activity in Android is one of the most important components of Android. It is the Activity where we put the UI of our application. So, if we are new to Android development then we should learn what an Activity is in Android and what is the lifecycle of an Activity. In this blog, we will learn about,
- What is an Activity in Android?
- What is the Activity Lifecycle?
- Real example use-cases of Activity Lifecycle.
What is an Activity in Android?
Whenever we open an Android application, then you see some UI drawn over our screen. That screen is called an Activity. It is the basic component of Android and whenever you are opening an application, then we are opening some activity.
For example, when we open our Gmail application, then we see our emails on the screen. Those emails are present in an Activity. If we open some particular email, then that email will be opened in some other Activity.
When we all started with coding, we know about the main method from where the program begins execution. Similarly, in Android, Activity is the one from where the Android Application starts its process. Activity is one screen of the app’s user interface. There is a series of methods that run in an activity.
There is a lifecycle associated with every Activity and to make an error-free Android application, we have to understand the lifecycle of Activity and write the code accordingly.
What is the Activity Lifecycle?
To understand the activity lifecycle, consider an example of a human being. As human beings, we go through certain stages of our life starting from as a kid to a teenager. From an adult and then to an old person. These are the phases or states of life we go through.
Similarly, for Activity in Android, we go through state changes in the total duration of the activity.
An Android activity undergoes through a number of states during its whole lifecycle. The following diagram shows the whole Activity lifecycle:
Image Credit: Android Website
The Activity lifecycle consists of 7 methods:
- onCreate() : When a user first opens an activity than the first method that gets called is called as onCreate. It acts the same as a constructor of a class, then when an activity is instantiated then onCreate gets called.
- onStart(): This method is called when an activity becomes visible to the user and is called after onCreate.
- onResume(): It is called just before the user starts interacting with the application.
- onPause(): It is called when the app is partially visible to the user on the mobile screen.
- onStop(): It is called when the activity is no longer visible to the user.
- onRestart(): It is called when the activity in the stopped state is about to start again.
- onDestroy(): It is called when the activity is cleared from the application stack.
So, these are the 7 methods that are associated with the lifecycle of an activity.
Real example use-cases of Activity Lifecycle
Now, let’s see real-life use-cases to understand the lifecycle for an activity.
When we open the activity for the first time, the sequence of state change it goes through is,
After this point, the activity is ready to be used by the user.
Now, let’s say we are minimizing the app by pressing the home button of the phone. The state changes it will go through is,
When we are moving to and from between activities, let’s say Activity A and Activity B. So, we will break it down in steps.
First, it opened Activity A, where the following states are called initially,
Then let’s say on a click of a button we opened Activity B. While opening Activity B, first, onPause will be called for Activity A and then,
will be called for Activity B. Then to finish this off, onStop of Activity A will be called and finally, Activity B would be loaded.
Now, when we press the back button from Activity B to Activity A, then first, onPause of Activity B is called and then,
gets called for Activity A and it is displayed to the user. Here you can see onRestart gets called rather then onCreate as it is restarting the activity and not creating it.
Then after onResume of Activity A is called then,
is called for Activity B and hence the activity is destroyed as the user has moved to Activity A.
Pressing the lock button while activity is on then,
gets called and when we reopen the app again,
When we kill the app from the recent app’s tray,
it gets called. Here you can see we are getting the onDestroy state getting called as we are killing the instance of the activity.
When we now reopen the activity, it will call onCreate and not onRestart to start the activity.
Consider a use-case where we need to ask permission from the user. Majority of the times we do it in onCreate .
Now, an edge case here is let’s say we navigate to a phone’s Settings app and deny the permission there, and then I came back to the initial app’s activity. Here, onCreate would not be called.
So, our permission check could not be satisfied here. To overcome this, onStart is the best place to put your permission check as it will handle the edge cases.
If you want to learn by video then, we at MindOrks have also created a video for you to make you understand Activity Lifecycle.
Источник
Activity in Android
In this tutorial we will leanr about one of the most important concept related to Android development, which is Activity.
What is an Activity in Android?
Human mind or concious is responsible for what we feel, what we think, makes us feel pain when we are hurt(physically or emotionally), which often leads to a few tears, laughing on seeing or hearing something funny and a lot more. What happens to us in the real world physically(getting hurt, seeing, hearing etc) are intrepeted by our mind(concious or soul) and we think or operate as per.
So in a way, we can say that our body is just a physical object while what controls us through every situation is our mind(soul or concious).
In case of Android → Views, Layouts and ViewGroups are used to design the user interface, which is the physical appearence of our App. But what is the mind or soul or concious of our App? Yes, it is the Activity.
Activity is nothing but a java class in Android which has some pre-defined functions which are triggered at different App states, which we can override to perform anything we want.
Activity class provides us with empty functions allowing us to be the controller of everything.
For example, if we have a function specified by our mind → onSeeingSomethingFunny() , although we know what happens inside this, but what if we can override and provide our own definition to this function.
One thing that is different here in context to our example is, that a human is created once at birth, and is destroyed once at death, and for the time in between is controlled by the mind/soul/concious. But an Activity is responsible to create and destroy an App infinite number of times. So apart from controlling the app, Activity also controls creation, destruction and other states of the App’s lifecycle.
There can be multiple Activities in Android, but there can be only one Main Activity. For example, In Java programming (or programming languages like C or C++), the execution of the program always begin with main() method. Similarly, when the user presses the App icon, the Main Activity is called and the execution starts from the onCreate() method of the Activity class.
Different States of App (or, the main App Activity)
Starting from a user clicking on the App icon to launch the app, to the user exiting from the App, there are certain defined states that the App is in, let’s see what they are.
- When a user clicks on the App icon, the Main Activity gets started and it creates the App’s User Interface using the layout XMLs. And the App or Activity starts running and it is said to be in ACTIVE state.
- When any dialog box appears on the screen, like when you press exit on some apps, it shows a box confirming whether you want to exit or not. At that point of time, we are not able to interact with the App’s UI until we deal with that dialog box/popup. In such a situation, the Activity is said to be in PAUSED state.
- When we press the Home button while using the app, our app doesn’t closes. It just get minimized. This state of the App is said to be STOPPED state.
- When we finally destroy the App i.e when we completely close it, then it is said to be in DESTROYED state.
Hence, all in all there are four states of an Activity(App) in Android namely, Active , Paused , Stopped and Destroyed .
From the user’s perspective, The activity is either visible, partially visible or invisible at a given point of time. So what happens when an Activity has one of the following visibility? We will learn about that, first let’s learn about these states in detail.
Active State
- When an Activity is in active state, it means it is active and running.
- It is visible to the user and the user is able to interact with it.
- Android Runtime treats the Activity in this state with the highest priority and never tries to kill it.
Paused State
- An activity being in this state means that the user can still see the Activity in the background such as behind a transparent window or a dialog box i.e it is partially visible.
- The user cannot interact with the Activity until he/she is done with the current view.
- Android Runtime usually does not kill an Activity in this state but may do so in an extreme case of resource crunch.
Stopped State
- When a new Activity is started on top of the current one or when a user hits the Home key, the activity is brought to Stopped state.
- The activity in this state is invisible, but it is not destroyed.
- Android Runtime may kill such an Activity in case of resource crunch.
Destroyed State
- When a user hits a Back key or Android Runtime decides to reclaim the memory allocated to an Activity i.e in the paused or stopped state, It goes into the Destroyed state.
- The Activity is out of the memory and it is invisible to the user.
Note: An Activity does not have the control over managing its own state. It just goes through state transitions either due to user interaction or due to system-generated events.
Activity Lifecycle methods
Whenever we open Google Maps app, it fetches our location through GPS. And if the GPS tracker is off, then Android will ask for your permission to switch it ON. So how the GPS tracker or Android is able to decide whether an app needs GPS tracker for functioning or not?
Yes, obviously, the App when started asks for the GPS location which is only possible if the GPS tracker in switched ON.
And how does the App knows this, because we coded it that whenever a user starts it, it has to ask the user to switch ON the GPS tracker, as it is required.
Similarly, we can also tell the app to perform a few things before exiting or getting destroyed.
This is the role of Activity Lifecycle. There are six key lifecycle methods through which every Activity goes depending upon its state. They are:
Method | What does it do? |
---|---|
onCreate() |