Android what activity is running

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:

  1. 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.
  2. onStart(): This method is called when an activity becomes visible to the user and is called after onCreate.
  3. onResume(): It is called just before the user starts interacting with the application.
  4. onPause(): It is called when the app is partially visible to the user on the mobile screen.
  5. onStop(): It is called when the activity is no longer visible to the user.
  6. onRestart(): It is called when the activity in the stopped state is about to start again.
  7. 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.

  1. 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.
  2. 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.
  3. 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.
  4. 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:

Whenever an Activity starts running, the first method to get executed is onCreate() . This method is executed only once during the lifetime. If we have any instance variables in the Activity, the initialization of those variables can be done in this method. After onCreate() method, the onStart() method is executed.

During the execution of onStart() method, the Activity is not yet rendered on screen but is about to become visible to the user. In this method, we can perform any operation related to UI components.

When the Activity finally gets rendered on the screen, onResume() method is invoked. At this point, the Activity is in the active state and is interacting with the user.

If the activity loses its focus and is only partially visible to the user, it enters the paused state. During this transition, the onPause() method is invoked. In the onPause() method, we may commit database transactions or perform light-weight processing before the Activity goes to the background.

From the active state, if we hit the Home key, the Activity goes to the background and the Home Screen of the device is made visible. During this event, the Activity enters the stopped state. Both onPause() and onStop() methods are executed.

When an activity is destroyed by a user or Android system, onDestroy() function is called.

When the Activity comes back to focus from the paused state, onResume() is invoked.

When we reopen any app(after pressing Home key), Activity now transits from stopped state to the active state. Thus, onStart() and onResume() methods are invoked.

Note: onCreate() method is not called, as it is executed only once during the Activity life-cycle.

To destroy the Activity on the screen, we can hit the Back key. This moves the Activity into the destroyed state. During this event, onPause() , onStop() and onDestroy() methods are invoked.

Note: Whenever we change the orientation of the screen i.e from portrait to landscape or vice-versa, lifecycle methods start from the start i.e from onCreate() method. This is because the complete spacing and other visual appearance gets changed and adjusted.

Источник

Памятка по жизненному циклу Android — часть I. Отдельные Activity

Android спроектирован так, чтобы использование приложения пользователем было максимально интуитивным. Например, пользователи приложения могут повернуть экран, ответить на уведомление или переключиться на другое приложение, и после этих манипуляций они все так же должны иметь возможность продолжить использовать приложение без каких-либо проблем.

Чтобы обеспечить такое взаимодействие с пользователем, вы должны знать, как управлять жизненными циклами компонентов. Компонентом может быть Activity, Fragment, Service, класс Application и даже сам процесс приложения. Компонент имеет жизненный цикл, в течение которого он проходит через различные состояния. Всякий раз, когда происходит переход, система уведомляет вас об этом при помощи методов жизненного цикла.

Чтобы нам было легче объяснить, как работает жизненный цикл в Android, мы определили несколько сценариев (примеров из жизни), которые сгруппированы по компонентам:

Часть 1: Activity — ЖЦ одного активити (этот пост)

Диаграммы также доступны в виде шпаргалки в формате PDF для краткого ознакомления.

Примечание: эти диаграммы соответствуют поведению в Android P/Jetpack 1.0.

Следующие сценарии демонстрируют поведение компонентов по умолчанию, если не указано иное.

Если вы обнаружили ошибки в статье или считаете, что не хватает чего-то важного, напишите об этом в комментариях.

Часть 1: Activity

Одно Aсtivity — Сценарий 1. Приложение завершено и перезапущено

Будет вызван, если:

Пользователь нажимает кнопку Назад или

Вызван метод Activity.finish()

Самый простой сценарий показывает, что происходит, когда приложение с одним активити запускается, завершается и перезапускается пользователем:

Управление состоянием

onSaveInstanceState не вызывается (поскольку активити завершено, вам не нужно сохранять состояние)

onCreate не имеет Bundle при повторном открытии приложения, потому что активити было завершено и состояние не нужно восстанавливать.

Одно Aсtivity — Сценарий 2. Пользователь уходит

Будет вызван, если:

Пользователь нажимает кнопку «Домой»

Пользователь переключается на другое приложение (через меню «Все приложения», из уведомления, при принятии звонка и т. д.)

В этом случае система остановит активити, но не завершит его сразу.

Управление состоянием

Когда ваше активити переходит в состояние Stopped, система использует onSaveInstanceState для сохранения состояния приложения на тот случай, если впоследствии система завершит процесс приложения (см. ниже).

Предполагая, что процесс не был убит, экземпляр активити сохраняется в памяти, сохраняя все состояние. Когда активити возвращается на передний план, вам не нужно повторно инициализировать компоненты, которые были созданы ранее.

Одно Aсtivity — Сценарий 3. Изменение кофигурации

Будет вызван, если:

Изменена конфигурация, такие как поворот экрана

Пользователь изменил размер окна в многооконном режиме

Управление состоянием

Изменения конфигурации, такие как поворот или изменение размера окна, должны позволить пользователям продолжить работу с того места, где они остановились.

Активити полностью уничтожено, но состояние сохраняется и восстанавливается при создании нового экземпляра.

Bundle в onCreate тот же самый, что и в onRestoreInstanceState .

Одно Aсtivity — Сценарий 4. Приложение приостановлено системой

Будет вызван, если:

Включён многооконный режим (API 24+) и потерян фокус

Другое приложение частично покрывает работающее приложение: диалоговое окно покупки (in-app purchases), диалоговое окно получения разрешения (Runtime Permission), стороннее диалоговое авторизации и т. д.

Появится окно выбора приложения (при обработке неявного интента), например диалоговое окно шейринга.

Этот сценарий не применим к:

Диалогам в том же приложении. Отображение AlertDialog или DialogFragment не приостанавливает базовое активити.

Уведомлениям. Пользователь, получающий новое уведомление или открывающий панель уведомлений, не приостанавливает текущее активити.

Источник

Читайте также:  Андроид пульт для аудиосистемы
Оцените статью
Method What does it do?
onCreate()