Android Hit Back Again to Exist Code Ex

A chore is a collection of activities that users interact with when trying to do something in your app. These activities are arranged in a stack—the dorsum stack—in the order in which each activeness is opened. For example, an email app might take one activity to prove a list of new messages. When the user selects a message, a new activity opens to view that bulletin. This new activeness is added to the back stack. Then, if the user presses or gestures Dorsum, that new action is finished and popped off the stack.

Lifecycle of a job and its back stack

The device Dwelling screen is the starting identify for near tasks. When a user touches the icon for an app or shortcut in the app launcher (or on the Abode screen), that app'southward task comes to the foreground. If no task exists for the app (the app has not been used recently), then a new job is created and the master action for that app opens as the root activity in the stack.

When the electric current activity starts another, the new activity is pushed on the peak of the stack and takes focus. The previous activity remains in the stack, but is stopped. When an activity stops, the system retains the current state of its user interface. When the user performs the back action, the current action is popped from the elevation of the stack (the activeness is destroyed) and the previous activity resumes (the previous state of its UI is restored). Activities in the stack are never rearranged, only pushed and popped from the stack—pushed onto the stack when started by the current activity and popped off when the user leaves it using the Back button or gesture. As such, the back stack operates as a terminal in, first out object structure. Figure 1 visualizes this behavior with a timeline showing the progress betwixt activities along with the current back stack at each betoken in time.

Figure i. A representation of how each new activity in a task adds an item to the dorsum stack. When the user presses or gestures Back, the current activity is destroyed and the previous activity resumes.

If the user continues to printing or gesture Dorsum, so each activeness in the stack is popped off to reveal the previous one, until the user returns to the Abode screen (or to whichever activeness was running when the job began). When all activities are removed from the stack, the task no longer exists.

Back press behavior for root launcher activities

Root launcher activities are activities that declare an Intent filter with both ACTION_MAIN and CATEGORY_LAUNCHER. These activities are unique because they deed as entry points into your app from the app launcher and are used to commencement a task.

When a user presses or gestures Back from a root launcher activity, the system handles the event differently depending on the version of Android that the device is running.

System behavior on Android xi and lower
The system finishes the action.
System behavior on Android 12 and higher

The system moves the activity and its task to the background instead of finishing the action. This behavior matches the default system behavior when navigating out of an app using the Home button or gesture.

In virtually cases, this behavior means that users tin more quickly resume your app from a warm state, instead of having to completely restart the app from a cold land.

If you need to provide custom back navigation, we recommend using the AndroidX Activity APIs, rather than overriding onBackPressed(). The AndroidX Activity APIs automatically defer to the appropriate system beliefs if there are no components intercepting the organization Dorsum press.

However, if your app overrides onBackPressed() to handle Back navigation and finish the activity, update your implementation to call through to super.onBackPressed() instead of finishing. Calling super.onBackPressed() moves the action and its task to the background when advisable and provides a more consistent navigation experience for users across apps.

Background and foreground tasks

Effigy two. Two tasks: Task B receives user interaction in the foreground, while Task A is in the background, waiting to exist resumed.

A chore is a cohesive unit of measurement that can move to the groundwork when a user begins a new job or goes to the Home screen. While in the background, all the activities in the task are stopped, just the dorsum stack for the task remains intact—the job has only lost focus while another task takes place, as shown in figure 2. A task can then render to the foreground so users can choice up where they left off.

Consider for example, the following task menses for a current chore (Task A) that has iii activities in its stack, including two under the electric current activity:

  1. The user uses the Home button or gesture, so starts a new app from the app launcher.

    When the Dwelling house screen appears, Task A goes into the background. When the new app starts, the system starts a task for that app (Chore B) with its own stack of activities.

  2. After interacting with that app, the user returns Domicile again and selects the app that originally started Task A.

    At present, Task A comes to the foreground—all three activities in its stack are intact and the activity at the top of the stack resumes. At this point, the user tin likewise switch back to Job B past going Home and selecting the app icon that started that task (or by selecting the app'south chore from the Recents screen).

Multiple action instances

Figure 3. A unmarried activity is instantiated multiple times.

Considering the activities in the back stack are never rearranged, if your app allows users to outset a particular activity from more than one activity, a new instance of that activity is created and pushed onto the stack (rather than bringing any previous instance of the activity to the top). As such, one activity in your app might be instantiated multiple times (even from unlike tasks), equally shown in figure 3. If the user navigates backward using the Back button or gesture, each case of the activity is revealed in the order they were opened (each with their ain UI state). However, yous can modify this behavior if you do not want an action to be instantiated more once. How to do so is discussed in the later section about managing tasks.

Multi-window environments

When apps are running simultaneously in a multi-windowed surroundings, supported in Android vii.0 (API level 24) and higher, the arrangement manages tasks separately for each window; each window may take multiple tasks. The aforementioned holds true for Android apps running on Chromebooks: the system manages tasks, or groups of tasks, on a per-window ground.

Lifecycle recap

To summarize the default behavior for activities and tasks:

  • When Action A starts Action B, Activeness A is stopped, just the organisation retains its country (such every bit whorl position and text entered into forms). If the user uses the Dorsum or gesture while in Activity B, Activity A resumes with its state restored.

  • When the user leaves a task using the Abode push or gesture, the electric current activity is stopped and its task goes into the background. The organization retains the country of every activity in the task. If the user later resumes the task by selecting the launcher icon that began the chore, the task comes to the foreground and resumes the activeness at the tiptop of the stack.

  • If the user presses or gestures Back, the current activity is popped from the stack and destroyed. The previous activity in the stack is resumed. When an activity is destroyed, the system does not retain the activity'south land.

    This behavior is different for root launcher activities when your app is running on a device that runs Android 12 or higher.

  • Activities can exist instantiated multiple times, even from other tasks.

Manage tasks

The way Android manages tasks and the back stack, as described above—by placing all activities started in succession in the aforementioned task and in a last in, first out stack—works great for most apps and yous shouldn't take to worry about how your activities are associated with tasks or how they be in the back stack. However, y'all might decide that you want to interrupt the normal behavior. Perhaps you want an action in your app to begin a new task when it is started (instead of being placed within the current task); or, when you kickoff an activity, you want to bring forward an existing instance of it (instead of creating a new instance on elevation of the back stack); or, you desire your back stack to be cleared of all activities except for the root activeness when the user leaves the task.

Y'all can practise these things and more than, with attributes in the <activity> manifest element and with flags in the intent that you lot pass to startActivity().

In this regard, these are the principal <activity> attributes that you tin utilize:

  • taskAffinity
  • launchMode
  • allowTaskReparenting
  • clearTaskOnLaunch
  • alwaysRetainTaskState
  • finishOnTaskLaunch

And these are the primary intent flags that you can use:

  • FLAG_ACTIVITY_NEW_TASK
  • FLAG_ACTIVITY_CLEAR_TOP
  • FLAG_ACTIVITY_SINGLE_TOP

In the following sections, you'll see how you tin use these manifest attributes and intent flags to ascertain how activities are associated with tasks and how they behave in the back stack.

Also, discussed separately are the considerations for how tasks and activities may exist represented and managed in the Recents screen. Run across Recents screen for more than data. Normally you should allow the system to ascertain how your task and activities are represented in the Recents screen, and yous don't need to alter this behavior.

Defining launch modes

Launch modes allow you to define how a new case of an activity is associated with the current task. Yous tin can define different launch modes in 2 ways:

  • Using the manifest file

    When yous declare an action in your manifest file, yous can specify how the activity should associate with tasks when it starts.

  • Using Intent flags

    When yous telephone call startActivity(), you can include a flag in the Intent that declares how (or whether) the new action should associate with the current task.

As such, if Activeness A starts Activeness B, Action B can define in its manifest how information technology should acquaintance with the electric current chore (if at all) and Activity A tin can also request how Action B should associate with electric current task. If both activities define how Action B should associate with a task, then Action A's request (as defined in the intent) is honored over Activity B's request (equally divers in its manifest).

Define launch modes using the manifest file

When declaring an activity in your manifest file, you tin specify how the activity should associate with a task using the <activity> element'south launchMode attribute.

The launchMode attribute specifies an instruction on how the activity should be launched into a chore. In that location are iv dissimilar launch modes you can assign to the launchMode attribute:

"standard" (the default manner)
Default. The system creates a new instance of the activity in the task from which it was started and routes the intent to it. The activeness can be instantiated multiple times, each instance tin can belong to different tasks, and 1 chore can have multiple instances.
"singleTop"

If an case of the activity already exists at the top of the current task, the arrangement routes the intent to that instance through a telephone call to its onNewIntent() method, rather than creating a new instance of the action. The action can be instantiated multiple times, each example tin can vest to different tasks, and 1 task tin can take multiple instances (but only if the activeness at the top of the dorsum stack is not an existing instance of the activity).

For instance, suppose a task'south back stack consists of root activity A with activities B, C, and D on top (the stack is A-B-C-D; D is on top). An intent arrives for an activity of blazon D. If D has the default "standard" launch mode, a new instance of the course is launched and the stack becomes A-B-C-D-D. Still, if D's launch mode is "singleTop", the existing case of D receives the intent through onNewIntent(), because it's at the top of the stack—the stack remains A-B-C-D. However, if an intent arrives for an activity of type B, then a new example of B is added to the stack, even if its launch manner is "singleTop".

"singleTask"

The system creates the action at the root of a new job or locates the activity on an existing task with the same affinity. If an instance of the action already exists and is at the root of the task, the system routes the intent to existing case through a call to its onNewIntent() method, rather than creating a new example. Meanwhile all of the other activities on superlative of information technology are destroyed.

"singleInstance".

Aforementioned as "singleTask", except that the system doesn't launch whatsoever other activities into the task holding the instance. The activity is ever the single and only fellow member of its task; any activities started by this 1 open in a separate task.

"singleInstancePerTask".

The activity can only exist running as the root activity of the task, the starting time activity that created the task, and therefore there will but be ane instance of this activity in a chore. In contrast to the singleTask launch mode, this activeness can be started in multiple instances in different tasks if the FLAG_ACTIVITY_MULTIPLE_TASK or FLAG_ACTIVITY_NEW_DOCUMENT flag is set.

Every bit another example, the Android Browser app declares that the web browser activity should always open up in its own job—by specifying the singleTask launch mode in the <action> element. This ways that if your app issues an intent to open the Android Browser, its action is not placed in the same task as your app. Instead, either a new chore starts for the Browser or, if the Browser already has a task running in the background, that task is brought forrad to handle the new intent.

Regardless of whether an activity starts in a new task or in the same task every bit the activity that started it, the Back button and gesture always take the user to the previous activeness. Nonetheless, if you start an activity that specifies the singleTask launch mode, then if an case of that activity exists in a background task, that whole chore is brought to the foreground. At this point, the dorsum stack now includes all activities from the task brought forward, at the top of the stack. Figure 4 illustrates this type of scenario.

Effigy iv. A representation of how an activity with launch way "singleTask" is added to the dorsum stack. If the activity is already a part of a background task with its ain dorsum stack, and then the entire back stack also comes forrard, on top of the electric current task.

For more than information about using launch modes in the manifest file, see the <activity> element documentation, where the launchMode attribute and the accepted values are discussed more than.

Define launch modes using Intent flags

When starting an activity, you tin can change the default clan of an activity to its task by including flags in the intent that y'all deliver to startActivity(). The flags yous can use to change the default beliefs are:

FLAG_ACTIVITY_NEW_TASK

Beginning the activity in a new task. If a job is already running for the activeness you are now starting, that task is brought to the foreground with its last state restored and the action receives the new intent in onNewIntent().

This produces the aforementioned beliefs as the "singleTask" launchMode value, discussed in the previous section.

FLAG_ACTIVITY_SINGLE_TOP

If the activeness beingness started is the current activity (at the top of the back stack), and then the existing instance receives a call to onNewIntent(), instead of creating a new case of the activity.

This produces the same behavior equally the "singleTop" launchMode value, discussed in the previous section.

FLAG_ACTIVITY_CLEAR_TOP

If the activeness being started is already running in the current task, so instead of launching a new instance of that activeness, all of the other activities on top of it are destroyed and this intent is delivered to the resumed instance of the activity (now on summit), through onNewIntent()).

There is no value for the launchMode attribute that produces this behavior.

FLAG_ACTIVITY_CLEAR_TOP is nigh often used in conjunction with FLAG_ACTIVITY_NEW_TASK. When used together, these flags are a way of locating an existing activity in another task and putting information technology in a position where it tin respond to the intent.

Handle affinities

An affinity indicates which task an activity prefers to belong to. By default, all the activities from the same app have an affinity for each other. And so, past default, all activities in the aforementioned app adopt to be in the same task. However, y'all can modify the default analogousness for an activity. Activities defined in unlike apps tin can share an analogousness, or activities divers in the same app tin can be assigned dissimilar job affinities.

You tin can change the affinity for any given activity with the taskAffinity attribute of the <action> element.

The taskAffinity aspect takes a string value, which must be unique from the default package name declared in the <manifest> element, because the system uses that name to identify the default task analogousness for the app.

The affinity comes into play in ii circumstances:

  • When the intent that launches an activity contains the FLAG_ACTIVITY_NEW_TASK flag.

    A new activity is, by default, launched into the task of the activity that called startActivity().

    It's pushed onto the same back stack as the caller. However, if the intent passed to startActivity()

    contains the FLAG_ACTIVITY_NEW_TASK flag, the organisation looks for a different task to house the new activity. Often, information technology'south a new task. However, information technology doesn't have to be. If there's already an existing task with the same affinity equally the new action, the action is launched into that task. If not, it begins a new task.

    If this flag causes an activity to brainstorm a new job and the user uses the Habitation button or gesture to leave it, there must exist some manner for the user to navigate dorsum to the task. Some entities (such as the notification manager) always outset activities in an external chore, never as part of their own, so they ever put FLAG_ACTIVITY_NEW_TASK in the intents they pass to startActivity(). If you have an activity that can exist invoked by an external entity that might use this flag, take care that the user has a independent mode to become dorsum to the task that'southward started, such as with a launcher icon (the root activeness of the task has a CATEGORY_LAUNCHER intent filter; meet the section on starting tasks).

  • When an activity has its allowTaskReparenting aspect set to "true".

    In this case, the activeness can move from the task information technology starts to the task information technology has an affinity for, when that task comes to the foreground.

    For example, suppose that an activity that reports weather weather condition in selected cities is defined as role of a travel app. It has the same affinity as other activities in the same app (the default app affinity) and information technology allows re-parenting with this attribute. When one of your activities starts the weather reporter activeness, it initially belongs to the same task as your activity. Notwithstanding, when the travel app's job comes to the foreground, the conditions reporter activity is reassigned to that task and displayed inside it.

Clear the back stack

If the user leaves a task for a long time, the arrangement clears the job of all activities except the root activity. When the user returns to the task over again, only the root activeness is restored. The system behaves this style, because, after an extended corporeality of time, users likely have abased what they were doing before and are returning to the chore to begin something new.

In that location are some activity attributes that you lot can utilize to modify this beliefs:

alwaysRetainTaskState
If this attribute is set to "true" in the root activeness of a job, the default beliefs just described does not happen. The task retains all activities in its stack even afterwards a long period.
clearTaskOnLaunch

If this attribute is set to "truthful" in the root activity of a chore, the chore is cleared downwardly to the root activeness whenever the user leaves the job and returns to it. In other words, information technology's the contrary of alwaysRetainTaskState. The user always returns to the task in its initial state, even after leaving the task for only a moment.

finishOnTaskLaunch

This attribute is like clearTaskOnLaunch, but it operates on a single activity, non an unabridged task. It can too cause whatever activity to finish, except for the root activeness. When information technology's set to "true", the activity remains part of the task only for the current session. If the user leaves and and so returns to the job, it is no longer present.

Start a task

Yous can set an action as the entry point for a job by giving it an intent filter with "android.intent.activity.MAIN" as the specified action and "android.intent.category.LAUNCHER" as the specified category. For case:

          <activity ... >     <intent-filter ... >         <action android:proper name="android.intent.activeness.MAIN" />         <category android:name="android.intent.category.LAUNCHER" />     </intent-filter>     ... </activity>                  

An intent filter of this kind causes an icon and label for the activity to be displayed in the app launcher, giving users a way to launch the activeness and to return to the task that it creates any time after it has been launched.

This 2d ability is important: Users must exist able to leave a job and then come back to information technology after using this activity launcher. For this reason, the 2 launch modes that mark activities equally always initiating a chore, "singleTask" and "singleInstance", should be used just when the action has an ACTION_MAIN and a CATEGORY_LAUNCHER filter. Imagine, for case, what could happen if the filter is missing: An intent launches a "singleTask" activity, initiating a new job, and the user spends some time working in that job. The user and then uses the Home button or gesture. The chore is now sent to the background and is not visible. Now the user has no manner to return to the chore, because it is non represented in the app launcher.

For those cases where yous don't desire the user to be able to return to an activeness, set the <activeness> element's finishOnTaskLaunch to "true" (see the section on clearing the dorsum stack).

Further information nigh how tasks and activities are represented and managed in the Overview screen is available in Recents screen.

More than resource

  • Pattern navigation graphs
  • <activity> manifest element
  • Recents screen

taylorfaing1939.blogspot.com

Source: https://developer.android.com/guide/components/activities/tasks-and-back-stack

0 Response to "Android Hit Back Again to Exist Code Ex"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel