Understanding of Activity startup mode

1. Understand Tasks and Back Stack

An App corresponds to a Task, and all activities in the app are arranged in a back stack.
In multi-window mode: There may be multiple Tasks under one Windows, and the system manages the Tasks for each window separately.

When starting an app, the system starts a Task for it. Other apps enter the background (acitivity in each stack is stopped). Note: If there are too many background tasks, the system will destroy the background activities to free memory, and the status of the activities will be lost.

2. Management tasks

The way Android manages tasks and the background stack, as mentioned above, by putting all activities in the same task and "last in first out" stack consecutively, is perfectly fine for most applications and doesn't have to worry about you activities are related to tasks or how they exit.

However, you may decide that you want to break this normal behavior:

  • Maybe you want an activity in your app to start a new task on startup (instead of being placed in the current task);
  • When starting an activity, you want to propose an existing instance of it, not create a new instance at the top of the stack;
  • When the user leaves the task, except for the root activity, want to clear the stack.

You can use attributes in the <activity> manifest element and flags in the intent passed to startActivity().

The principal <activity>properties as follows:

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

The main intent flags you can use are:

  • FLAG_ACTIVITY_NEW_TASK
  • FLAG_ACTIVITY_CLEAR_TOP
  • FLAG_ACTIVITY_SINGLE_TOP

3. Define the startup mode

In Android, each interface is an Activity, and the switching interface operation is actually an instantiation operation between multiple different Activities. In Android, the startup mode of an Activity determines the startup mode of an Activity.

Launch modes allow you to define how new instances of an activity are associated with the current task. You can define different boot modes in two ways:

  • Using the manifest file
    When declaring an activity in the manifest file, you can specify how the activity should be associated with the task when it starts.
  • Intent flags
    When called startActivity(), you can include a flag in the intent stating how (or if) the new activity is associated with the current task.

So, if Activity A starts Activity B, Activity B can define in its manifest how it should be associated with the current task (if any), and Activity A can also request how Activity B should be associated with the current task. If both activities define how Activity B should be associated with the task, then Activity A's request (as defined in the intent) will be granted to Activity B's request (as defined in the manifest).

Note: some startup modes are available in manifest files, but not as flags for intents; similarly, some startup modes are available as flags, but cannot be defined in the manifest.

Use manifest file

Activity startup mode settings:

<activity android:name=".MainActivity" android:launchMode="standard" />

There are four startup modes of Activity:

  1. standard (default mode)
    The system creates a new instance of the activity in the launched task and routes the intent to that task.
    The activity can be instantiated multiple times, each instance can belong to a different task, and a task can have multiple instances.

  2. singleTop
    If an instance of the activity already exists on top of the current task, the system routes the intent to that instance by calling its onNewIntent()method instead of creating a new instance of the activity.

The activity can be instantiated multiple times, each instance can belong to a different task, and a task can have multiple instances (but only if the activity at the top of the back stack is not an existing instance of the activity).

  1. The singleTask
    system creates a new task and instantiates the new task's root activity. However, if an instance of the activity already exists in a separate task, the system routes the intent to the existing instance by calling its onNewIntent()method , rather than creating a new instance. Only one active instance can exist at a time.

Note: Although the activity is launched in a new task, the back button still returns the user to the previous activity.

  1. singleInstance
    is the same as "singleTask" except that the system does not put any other activities into the instance. The activity is always the only member of its task, and any activities started by the activity are opened in a separate task.

Create the Activity instance in a new stack and let multiple applications share the Activity instance in the new stack. Once the instance of the Activity that changes the mode exists in a certain stack, any application will reuse the instance in the stack when the Activity is activated again. The effect is equivalent to that of multiple applications sharing an application. in application.

Example

1.standard

public class MainActivity extends AppCompatActivity {

    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = findViewById(R.id.textView);
        tv.setText(this.toString());

    }
   
    // 按钮点击事件
    public void launchStandard(View view) {
        startActivity(new Intent(this, MainActivity.class));
        tv.setText(this.toString());
    }
}

Enter image description

It can be seen that this Standardmode creates a new Activity object every time. When the back button is clicked, it will destroy the top of the stack (the current Activity) and then jump to the next level. This mode may not be what we need in most cases, because it consumes too much system performance.

**2.singleTop **
You can know from the above explanation that every time you use a new Activity, it will automatically detect whether the current Activity at the top of the stack is the Activity that needs to be referenced. Create a new Activity.

 <activity
            android:name=".SingleTopActivity"
            android:launchMode="singleTop"
            android:screenOrientation="portrait" />

public class MainActivity extends AppCompatActivity {

    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = findViewById(R.id.textView);
        tv.setText(this.toString());

    }

    public void launchStandard(View view) {
        startActivity(new Intent(this, SingleTopActivity.class));
        tv.setText(this.toString());

    }
}

public class SingleTopActivity extends AppCompatActivity {

    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_single_top);
        tv = findViewById(R.id.textView);
        tv.setText(this.toString());
    }

   @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Toast.makeText(this,this.getClass().getSimpleName(),Toast.LENGTH_LONG).show();
    }

    public void launchSingleTop(View view) {
        startActivity(new Intent(this, SingleTopActivity.class));
        tv.setText(this.toString());
    }
}

Enter image description

When the SingleTopActivity"start current page button" is clicked, no new object will be created, because the Activity is on the top of the stack, no new object will be created, but the onNewIntent()method    .

3.singleTask

The difference between this startup mode and singleTop can be seen in the name, that is, singleTop only detects whether the Activity at the top of the current stack is what we need to request to create each time, while singleTask will detect all Activity objects in the stack, from top to bottom, If it is detected that it is what we requested, the object above the Activity object will be destroyed, and the detected Activity we need will be directly placed on the top of the stack.

** 4.SingleInstance**

This startup mode works similarly to the browser we use. We all know that when accessing the browser in multiple programs, if the current browser is not open, the browser will be opened, otherwise it will be accessed in the currently opened browser. This mode will save a lot of system resources, because it can ensure that there is only one Activity object to be requested in the current stack.

The above are the four startup modes in Android, which we often use when developing Android projects. Cleverly setting the startup mode of Activity will save system overhead and program running efficiency.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325290662&siteId=291194637