- Остановка и перезапуск Activity
- В этом уроке
- Вы также должны прочитать
- Попробуйте
- Остановка вашей activity
- Перезагрузить активность в Android
- 14 ответов
- Памятка по жизненному циклу Android — часть I. Отдельные Activity
- Часть 1: Activity
- Одно Aсtivity — Сценарий 1. Приложение завершено и перезапущено
- Одно Aсtivity — Сценарий 2. Пользователь уходит
- Одно Aсtivity — Сценарий 3. Изменение кофигурации
- Одно Aсtivity — Сценарий 4. Приложение приостановлено системой
- Restart activity android studio
Остановка и перезапуск Activity
В этом уроке
Вы также должны прочитать
Попробуйте
Правильная остановка и перезапуск вашей activity является важным процессом жизненного цикла activity , который дает пользователям чувство, что ваше приложение всегда живое и не теряет их прогресс. Есть несколько ключевых сценариев, в которых ваша activity останавливается и перезапускается:
- Пользователь открывает окно Недавние приложения и переключается с вашего приложения на другое приложение. activity вашего приложения, находящаяся в это время на переднем плане, останавливается. Если пользователь возвращается в ваше приложении с помощью значка запуска главного экрана или окна Недавние приложения, activity перезагружается.
- Пользователь выполняет действие в вашем приложении, которое начинается новую activity . Текущая activity будет остановлена, когда вторая activity будет создана. Если пользователь затем нажимает кнопку Назад , первая activity перезапустится.
- Пользователь получает телефонный звонок во время использования приложения на его или ее телефоне.
Activity класс предоставляет два метода жизненного цикла, onStop() и onRestart() , которые позволяют специально обрабатывать то, как ваша activity будет останавливаться и перезапускаться. В отличие от состояния приостановки, которое означает частичное перекрытие элементов пользовательского интерфейса, состояние остановки vгарантирует, что пользовательский интерфейс больше не виден и фокус пользователя находится в другой activity (или совершенно другом приложении).
Примечание: Поскольку система удерживает ваш Activity экземпляр в системной памяти, когда он остановлен, вполне возможно, что вам не нужно реализовывать onStop() и onRestart() (или даже onStart() методы вообще. Для большинства activity , которые относительно простые, activity будет остановлена и перезапущена вполне нормально, и вы, возможно, должны использовать только onPause() для приостановки текущих действий и отсоединения от системных ресурсов.
Рисунок 1. Когда пользователь покидает вашу activity , система вызывает onStop() для прекращения activity (1). Если пользователь возвращается по время остановки activity , система вызывает onRestart() (2), а затем быстро onStart() (3) и onResume() (4). Обратите внимание, что независимо от того, какой сценарий вызывает остановку activity , система всегда вызывает onPause() перед вызовом onStop() .
Остановка вашей activity
Когда ваша activity получает вызов onStop() метода, уже ничего не видно и вы должны освободить почти все ресурсы, которые не нужны, пока пользователь их не использует. После того, как ваша activity прекращается, система может уничтожить экземпляр, если это необходимо для восстановления системной памяти. В крайних случаях, система может просто убить ваш процесс приложения без вызова финального onDestroy() метода обратного вызова, поэтому очень важно использовать onStop() для освобождения ресурсов, которые могли бы привести к утечке памяти.
Несмотря на то, что onPause() метод вызывается до onStop() , вы должны использовать onStop() для выполнения более крупных и ресурсоемких операций завершения, таких как запись информации в базу данных.
Например, вот реализация onStop() , который сохраняет содержимое черновика записки в постоянное хранилище:
Источник
Перезагрузить активность в Android
это хорошая практика, чтобы перезагрузить Activity на Android?
что было бы лучшим способом сделать это? this.finish а то this.startActivity активность Intent ?
14 ответов
Вы можете просто использовать
обновление Activity изнутри.
это то, что я делаю, чтобы перезагрузить действие после изменения возврата из изменения предпочтений.
это по существу заставляет активность перерисовывать себя.
обновление: лучший способ сделать это-вызвать recreate() метод. Это приведет к воссозданию активности.
для тех, кто не хочет видеть, что мигает после recreate () метод просто использовать
Мне нужно было срочно обновить список сообщений в одном из моих приложений, поэтому я просто выполнил обновление моей основной активности пользовательского интерфейса, прежде чем закрыть диалоговое окно, в котором я был. Я уверен, что есть и лучшие способы добиться этого.
Android включает в себя систему управления процессами, которая обрабатывает создание и уничтожение деятельности, которая в значительной степени отрицает любую выгоду, которую вы увидите от ручного перезапуска деятельности. Вы можете посмотреть дополнительную информацию о нем по адресу Основы Применения
хорошая практика заключается в том, чтобы гарантировать, что ваши методы onPause и onStop освобождают любые ресурсы, которые вам не нужно удерживать и использовать onLowMemory уменьшить ваши потребности деятельностей до абсолютного минимума.
Источник
Памятка по жизненному циклу 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 не приостанавливает базовое активити.
Уведомлениям. Пользователь, получающий новое уведомление или открывающий панель уведомлений, не приостанавливает текущее активити.
Источник
Restart activity android studio
The default value of this attribute is false . android:allowTaskReparenting Whether or not the activity can move from the task that started it to the task it has an affinity for when that task is next brought to the front — » true » if it can move, and » false » if it must remain with the task where it started.
If this attribute is not set, the value set by the corresponding allowTaskReparenting attribute of the element applies to the activity. The default value is » false «.
Normally when an activity is started, it’s associated with the task of the activity that started it and it stays there for its entire lifetime. You can use this attribute to force it to be re-parented to the task it has an affinity for when its current task is no longer displayed. Typically, it’s used to cause the activities of an application to move to the main task associated with that application.
For example, if an e-mail message contains a link to a web page, clicking the link brings up an activity that can display the page. That activity is defined by the browser application, but is launched as part of the e-mail task. If it’s reparented to the browser task, it will be shown when the browser next comes to the front, and will be absent when the e-mail task again comes forward.
The affinity of an activity is defined by the taskAffinity attribute. The affinity of a task is determined by reading the affinity of its root activity. Therefore, by definition, a root activity is always in a task with the same affinity. Since activities with » singleTask » or » singleInstance » launch modes can only be at the root of a task, re-parenting is limited to the » standard » and » singleTop » modes. (See also the launchMode attribute.)
android:alwaysRetainTaskState Whether or not the state of the task that the activity is in will always be maintained by the system — » true » if it will be, and » false » if the system is allowed to reset the task to its initial state in certain situations. The default value is » false «. This attribute is meaningful only for the root activity of a task; it’s ignored for all other activities.
Normally, the system clears a task (removes all activities from the stack above the root activity) in certain situations when the user re-selects that task from the home screen. Typically, this is done if the user hasn’t visited the task for a certain amount of time, such as 30 minutes.
However, when this attribute is » true «, users will always return to the task in its last state, regardless of how they get there. This is useful, for example, in an application like the web browser where there is a lot of state (such as multiple open tabs) that users would not like to lose.
android:autoRemoveFromRecents Whether or not tasks launched by activities with this attribute remains in the overview screen until the last activity in the task is completed. If true , the task is automatically removed from the overview screen. This overrides the caller’s use of FLAG_ACTIVITY_RETAIN_IN_RECENTS . It must be a boolean value, either » true » or » false «. android:banner A drawable resource providing an extended graphical banner for its associated item. Use with the tag to supply a default banner for a specific activity, or with the tag to supply a banner for all application activities.
The system uses the banner to represent an app in the Android TV home screen. Since the banner is displayed only in the home screen, it should only be specified by applications with an activity that handles the CATEGORY_LEANBACK_LAUNCHER intent.
This attribute must be set as a reference to a drawable resource containing the image (for example «@drawable/banner» ). There is no default banner.
See Provide a home screen banner in Get Started with TV Apps for more information.
android:clearTaskOnLaunch Whether or not all activities will be removed from the task, except for the root activity, whenever it is re-launched from the home screen — » true » if the task is always stripped down to its root activity, and » false » if not. The default value is » false «. This attribute is meaningful only for activities that start a new task (the root activity); it’s ignored for all other activities in the task.
When the value is » true «, every time users start the task again, they are brought to its root activity regardless of what they were last doing in the task and regardless of whether they used the Back or Home button to leave it. When the value is » false «, the task may be cleared of activities in some situations (see the alwaysRetainTaskState attribute), but not always.
Suppose, for example, that someone launches activity P from the home screen, and from there goes to activity Q. The user next presses Home, and then returns to activity P. Normally, the user would see activity Q, since that is what they were last doing in P’s task. However, if P set this flag to » true «, all of the activities on top of it (Q in this case) would be removed when the user launched activity P from the home screen. So the user would see only P when returning to the task.
If this attribute and allowTaskReparenting are both » true «, any activities that can be re-parented are moved to the task they share an affinity with; the remaining activities are then dropped, as described above.
This attribute is ignored if FLAG_ACTIVITY_RESET_TASK_IF_NEEDED is not set.
Requests the activity to be displayed in wide color gamut mode on compatible devices. In wide color gamut mode, a window can render outside of the SRGB gamut to display more vibrant colors. If the device doesn’t support wide color gamut rendering, this attribute has no effect. For more information about rendering in wide color mode, see Enhancing Graphics with Wide Color Content.
android:configChanges Lists configuration changes that the activity will handle itself. When a configuration change occurs at runtime, the activity is shut down and restarted by default, but declaring a configuration with this attribute will prevent the activity from being restarted. Instead, the activity remains running and its onConfigurationChanged() method is called.
Note: Using this attribute should be avoided and used only as a last resort. Please read Handling Runtime Changes for more information about how to properly handle a restart due to a configuration change.
Any or all of the following strings are valid values for this attribute. Multiple values are separated by ‘ | ‘ — for example, » locale|navigation|orientation «.
Value | Description | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
» density « | The display density has changed — the user might have specified a different display scale, or a different display might now be active. Added in API level 24. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» fontScale « | The font scaling factor has changed — the user has selected a new global font size. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» keyboard « | The keyboard type has changed — for example, the user has plugged in an external keyboard. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» keyboardHidden « | The keyboard accessibility has changed — for example, the user has revealed the hardware keyboard. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» layoutDirection « | The layout direction has changed — for example, changing from left-to-right (LTR) to right-to-left (RTL). Added in API level 17. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» locale « | The locale has changed — the user has selected a new language that text should be displayed in. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» mcc « | The IMSI mobile country code (MCC) has changed — a SIM has been detected and updated the MCC. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» mnc « | The IMSI mobile network code (MNC) has changed — a SIM has been detected and updated the MNC. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» navigation « | The navigation type (trackball/dpad) has changed. (This should never normally happen.) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» orientation « | The screen orientation has changed — the user has rotated the device. Note: If your application targets Android 3.2 (API level 13) or higher, then you should also declare the «screenSize» and «screenLayout» configurations, because they might also change when a device switches between portrait and landscape orientations. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» screenLayout « | The screen layout has changed — a different display might now be active. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» screenSize « | The current available screen size has changed. This represents a change in the currently available size, relative to the current aspect ratio, so will change when the user switches between landscape and portrait. Added in API level 13. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» smallestScreenSize « | The physical screen size has changed. This represents a change in size regardless of orientation, so will only change when the actual physical screen size has changed such as switching to an external display. A change to this configuration corresponds to a change in the smallestWidth configuration. Added in API level 13. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» touchscreen « | The touchscreen has changed. (This should never normally happen.) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» uiMode « | The user interface mode has changed — the user has placed the device into a desk or car dock, or the night mode has changed. For more information about the different UI modes, see UiModeManager . Added in API level 8. All of these configuration changes can impact the resource values seen by the application. Therefore, when onConfigurationChanged() is called, it will generally be necessary to again retrieve all resources (including view layouts, drawables, and so on) to correctly handle the change. Note: To handle all Multi-Window related configuration changes use both «screenLayout» and «smallestScreenSize» . Multi-Window is supported in Android 7.0 (API level 24) or higher. Whether or not the activity is direct-boot aware; that is, whether or not it can run before the user unlocks the device. Note: During Direct Boot, an activity in your application can only access the data that is stored in device protected storage. The default value is «false» . android:documentLaunchMode Specifies how a new instance of an activity should be added to a task each time it is launched. This attribute permits the user to have multiple documents from the same application appear in the overview screen. This attribute has four values which produce the following effects when the user opens a document with the application:
Note: For values other than » none » and » never » the activity must be defined with launchMode=»standard» . If this attribute is not specified, documentLaunchMode=»none» is used. android:enabled Whether or not the activity can be instantiated by the system — «true» if it can be, and » false » if not. The default value is » true «. android:excludeFromRecents Whether or not the task initiated by this activity should be excluded from the list of recently used applications, the overview screen. That is, when this activity is the root activity of a new task, this attribute determines whether the task should not appear in the list of recent apps. Set » true » if the task should be excluded from the list; set » false » if it should be included. The default value is » false «. android:exported This element sets whether the activity can be launched by components of other applications:
If an activity in your app includes intent filters, set this element to » true » to allow other apps to start it. For example, if the activity is the main activity of the app and includes the category » android.intent.category.LAUNCHER «. If this element is set to » false » and an app tries to start the activity, the system throws an ActivityNotFoundException . This attribute is not the only way to limit an activity’s exposure to other applications. Permissions can also be used to limit the external entities that can invoke the activity (see the permission attribute). android:finishOnTaskLaunch Whether or not an existing instance of the activity should be shut down (finished), except for the root activity, whenever the user again launches its task (chooses the task on the home screen) — » true » if it should be shut down, and » false » if not. The default value is » false «. If this attribute and allowTaskReparenting are both » true «, this attribute trumps the other. The affinity of the activity is ignored. The activity is not re-parented, but destroyed. This attribute is ignored if FLAG_ACTIVITY_RESET_TASK_IF_NEEDED isn’t set. android:hardwareAccelerated Whether or not hardware-accelerated rendering should be enabled for this Activity — » true » if it should be enabled, and » false » if not. The default value is » false «. Starting from Android 3.0, a hardware-accelerated OpenGL renderer is available to applications, to improve performance for many common 2D graphics operations. When the hardware-accelerated renderer is enabled, most operations in Canvas, Paint, Xfermode, ColorFilter, Shader, and Camera are accelerated. This results in smoother animations, smoother scrolling, and improved responsiveness overall, even for applications that do not explicitly make use the framework’s OpenGL libraries. Because of the increased resources required to enable hardware acceleration, your app will consume more RAM. Note that not all of the OpenGL 2D operations are accelerated. If you enable the hardware-accelerated renderer, test your application to ensure that it can make use of the renderer without errors. android:icon An icon representing the activity. The icon is displayed to users when a representation of the activity is required on-screen. For example, icons for activities that initiate tasks are displayed in the launcher window. The icon is often accompanied by a label (see the android:label attribute). This attribute must be set as a reference to a drawable resource containing the image definition. If it is not set, the icon specified for the application as a whole is used instead (see the element’s icon attribute). android:immersive Sets the immersive mode setting for the current activity. If the android:immersive attribute is set to true in the app’s manifest entry for this activity, the ActivityInfo.flags member always has its FLAG_IMMERSIVE bit set, even if the immersive mode is changed at runtime using the setImmersive() method. android:label A user-readable label for the activity. The label is displayed on-screen when the activity must be represented to the user. It’s often displayed along with the activity icon. If this attribute is not set, the label set for the application as a whole is used instead (see the element’s label attribute). The label should be set as a reference to a string resource, so that it can be localized like other strings in the user interface. However, as a convenience while you’re developing the application, it can also be set as a raw string. android:launchMode An instruction on how the activity should be launched. There are four modes that work in conjunction with activity flags ( FLAG_ACTIVITY_* constants) in Intent objects to determine what should happen when the activity is called upon to handle an intent. They are: » standard » The default mode is » standard «. As shown in the table below, the modes fall into two main groups, with » standard » and » singleTop » activities on one side, and » singleTask » and » singleInstance » activities on the other. An activity with the » standard » or » singleTop » launch mode can be instantiated multiple times. The instances can belong to any task and can be located anywhere in the activity stack. Typically, they’re launched into the task that called startActivity() (unless the Intent object contains a FLAG_ACTIVITY_NEW_TASK instruction, in which case a different task is chosen — see the taskAffinity attribute). In contrast, » singleTask » and » singleInstance » activities can only begin a task. They are always at the root of the activity stack. Moreover, the device can hold only one instance of the activity at a time — only one such task. The » standard » and » singleTop » modes differ from each other in just one respect: Every time there’s a new intent for a » standard » activity, a new instance of the class is created to respond to that intent. Each instance handles a single intent. Similarly, a new instance of a » singleTop » activity may also be created to handle a new intent. However, if the target task already has an existing instance of the activity at the top of its stack, that instance will receive the new intent (in an onNewIntent() call); a new instance is not created. In other circumstances — for example, if an existing instance of the » singleTop » activity is in the target task, but not at the top of the stack, or if it’s at the top of a stack, but not in the target task — a new instance would be created and pushed on the stack. Similarly, if you navigate up to an activity on the current stack, the behavior is determined by the parent activity’s launch mode. If the parent activity has launch mode singleTop (or the up intent contains FLAG_ACTIVITY_CLEAR_TOP ), the parent is brought to the top of the stack, and its state is preserved. The navigation intent is received by the parent activity’s onNewIntent() method. If the parent activity has launch mode standard (and the up intent does not contain FLAG_ACTIVITY_CLEAR_TOP ), the current activity and its parent are both popped off the stack, and a new instance of the parent activity is created to receive the navigation intent. The » singleTask » and » singleInstance » modes also differ from each other in only one respect: A » singleTask » activity allows other activities to be part of its task. It’s always at the root of its task, but other activities (necessarily » standard » and » singleTop » activities) can be launched into that task. A » singleInstance » activity, on the other hand, permits no other activities to be part of its task. It’s the only activity in the task. If it starts another activity, that activity is assigned to a different task — as if FLAG_ACTIVITY_NEW_TASK was in the intent.
As shown in the table above, standard is the default mode and is appropriate for most types of activities. SingleTop is also a common and useful launch mode for many types of activities. The other modes — singleTask and singleInstance — are not appropriate for most applications , since they result in an interaction model that is likely to be unfamiliar to users and is very different from most other applications. Regardless of the launch mode that you choose, make sure to test the usability of the activity during launch and when navigating back to it from other activities and tasks using the Back button. For more information on launch modes and their interaction with Intent flags, see the Tasks and Back Stack document. android:lockTaskMode Determines how the system presents this activity when the device is running in lock task mode. Android can run tasks in an immersive, kiosk-like fashion called lock task mode. When the system runs in lock task mode, device users typically can’t see notifications, access non-allowlisted apps, or return to the home screen (unless the Home app is allowlisted). Only apps that have been allowlisted by a device policy controller (DPC) can run when the system is in lock task mode. System and privileged apps, however, can run in lock task mode without being allowlisted. The value can be any one of the following R.attr.lockTaskMode string values:
|