Activity analysis of the four major components of Android (on)

I. Overview

Simply put, Activity is a visual interface, responsible for building a screen window to prevent UI components for user interaction. Generally speaking, there are three steps to construct Activity:

  1. Contract to build Activity class;
  2. Register in AndroidManifest.xml;
  3. Set the layout file (optional).

2. How to start Activity

2.1, display startup

Clearly specify the class of the Activity to be started \color{red}{class}C L A S S orpackage names. activity class name \ color {red} {} class name package names .activityPackage name . a c t i v i t y class name , there are three main ways to display startup:

  • Method 1: class jump (most commonly used)
    Intent intent = new Intent(MainActivity.this, SecondActivity.class);
    startActivity(intent);
    
  • Method 2: package name. class name jump
    Intent intent = new Intent();
    intent.setClassName(MainActivity.this, "com.zjgsu.activitydemo.SecondActivity");
    startActivity(intent);
    
  • Method 3: ComponentName jump
    Intent intent = new Intent();
    intent.setComponent(new ComponentName(MainActivity.this, SecondActivity.class));
    startActivity(intent);
    

2.2, implicit start

Set the startup filter, through the specified action \color{red}{action}action a c t i o n 和 d a t a \color{red}{action 和 data} A C T I O n- and D A T A properties, will find qualified Activity, and start it, there are two ways to start the privacy:

  • Method 1: Pass in actionName
    Intent intent = new Intent("abcd.SecondActivity");
    startActivity(intent);
    
  • Method 2: Set action
    Intent intent = new Intent();
    intent.setAction("abcd.SecondActivity");
    startActivity(intent);
    

Note: If an activity defined by yourself is to be started implicitly, android.intent.category.DEFAULT must be added to AndroidManifest.xml, otherwise it will not work.

 <activity android:name=".SecondActivity">
     <intent-filter>
         <action android:name="abcd.SecondActivity"/>
         <category android:name="android.intent.category.DEFAULT"/>
     </intent-filter>
 </activity>

2.2.1. What happens if the actionName of two activities are the same when implicitly started?

As shown below, I created two activities, then I set the actionName of these two activities to be the same, and then I start the activity implicitly, what will happen?

<activity android:name=".SecondActivity"
   android:label="第二个界面">
    <intent-filter>
        <action android:name="abcd.SecondActivity" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

<activity android:name=".ThirdActivity"
    android:label="第三个界面">
    <intent-filter>
        <action android:name="abcd.SecondActivity" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

The running effect is as follows:


Implicitly start Activity
we can see from the above gif animation, in this case, Android will let us choose the Activity to run. That is, when there are multiple Actions that match the implicitly matched conditions, a selection box will pop up for the user to choose.

Three, the life cycle of Activity

Let's take the following Activity life cycle diagram as an example:


When an activity starts, it will call onCreate() --> onStart() --> onResume() --> onPause() --> onStop() --> onDestroy() in turn. When onResume() is executed, the Activity becomes operational.

3.1, the calling sequence of a single Activity life cycle

  • onCreate() is called when the Activity is created
  • onStart() is called when the Activity interface becomes visible to the user
  • onResume() is called when the Activity interface gets the focus (the interface button can be clicked, the text box can be input, etc.)
  • onPause() is called when the Activity interface loses focus ( interface buttons cannot be clicked, text boxes cannot be entered, etc.)
  • onStop() is called when the Activity interface becomes invisible to the user
  • onDestroy() is called when the Activity is destroyed
  • onRestart() is called when the Activity starts again

3.2, call sequence of multiple Activity life cycle

The life cycle of multiple activities is shown in the following figure:
Multi-Activity life cycle
The operation flow of the above figure: open A activity, click the button to start B activity, and click the return button in B activity. The code running screenshot is as follows:
simulation

Fourth, the startup mode of Activity

The startup mode of the Activity determines whether the newly produced Activity instance reuses the existing Activity instance and whether it shares a Task with other Activity instances. Task is an object with a stack structure. A Task can manage multiple Activities, start an application, and create a corresponding Task.

4.1. Four startup modes

  1. The standard
    default startup mode, each time Activity is activated (startActivity), an Activity instance is created and placed in the task stack;
  2. Each time singleTop
    activates an Activity, it determines whether the Activity instance is on the top of the stack. If it is, it does not need to be created. Otherwise, it is necessary to create an Activity instance;
  3. SingleTask
    If the Activity to be activated already exists in the task stack, you don’t need to create it. You only need to pop the Activity instances above this Activity from the stack. At this time, the Activity will reach the top of the stack. If it does not exist, create the Activity Instance
  4. There is only one instance of singleInstance
    , and this instance runs independently in a Task, this Task has only this instance, and no other Activity instances are allowed.

4.2, four start mode code demonstration

4.2.1、standard

Let's take a look at the effect first:

Insert picture description here
you can see that in SecondActivity, start SecondActivity again, and the start method in standard mode will create SecondActivity instance again. Makes the task stack contains two SecondActivity instances, so we click the return button to return to the previous SecondActivity, and press the return button again to return to MainActivity.

The main code is as follows:

// 启动模式是 standard,不填默认就是 standard
<activity android:name=".SecondActivity"
	android:launchMode="standard"/>

// SecondActivity
public class SecondActivity extends AppCompatActivity {
    
    

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

        findViewById(R.id.btn_start_self).setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                startActivity(new Intent(SecondActivity.this, SecondActivity.class));
            }
        });
    }
}

4.2.2、singleTop

We still use the above example to demonstrate, just change the startup mode of SecondActivity to singleTop, let's see the effect:

Insert picture description here
you can see that if you start yourself again in SecondActivity at this time, SecondActivity instance will not be created, it should be this time SecondActivity Already at the top of the stack, and the singleTop startup mode will determine whether the Activity instance is on the top of the stack, if it is, it does not need to be created, otherwise it will create the Activity instance.

The main code is as follows:

<activity android:name=".SecondActivity"
	android:launchMode="singleTop"/>

Question 1 : If we create a ThirdActivity at this time, start SecondActivity in MainActivity, then start ThirdActivity in SecondActivity, and then start SecondActivity in ThirdActivity, what is the order of the instances of Activity in the task stack at this time?

Answer : The bottom-up Activity instance sequence in the task stack is MainActivity–>SecondActivity–>ThirdActivity–>SecondActivity.

4.2.3、singleTask

We use the example of the above question to demonstrate, just change the startup mode of SecondActivity to singleTask, let's see the effect: At

Insert picture description here
this time, the order of the bottom-up Activity instances in the task stack is MainActivity–>SecondActivity. Because of the SingleTask startup mode, if there are Activity instances in the stack, all Activity instances above the Activity will be popped out of the stack.

The main code is as follows:

<activity android:name=".SecondActivity"
	android:launchMode="singleTask"/>

4.2.4、singleInstance

The singleInstance startup mode is a bit similar to the singleTask startup mode. Both ensure that there is only one instance of the same Activity in the task stack, but singleInstance will create a new Task. To demonstrate singleInstance, we need to print out the ID of the stack where each Activity is located. The example is the same as above, except that the startup mode is changed to singleInstance.

The print log is as follows:
singleInstance
We see that the TaskId of the task stack where SecondActivity is located is 592, and the TaskId of the task stack where MainActivity and ThirdActivity are located is 591. This means that SecondActivity runs in an independent task stack, and there is only one Activity instance of SecondActivity in this task stack. The method of printing TaskId is as follows:

Log.e("activityDemo2TAG", "ThirdActivity所在的task的id为:" + getTaskId());

Five, use IntentFlag to set the startup method of Activity

Before explaining this knowledge point, let's take a look at the two concepts of Task and taskAffinity.

5.1, Task basic concepts

  • Task is a container with a stack structure, which can place multiple Activity instances;
  • Start an application, the system will create a Task for it to place the root Activity;
  • When an activity starts another activity, the two activities are placed in the same Task by default. The latter is pushed into the Task stack where the former is located. When the user presses the return button, the latter is ejected from the Task, the former It is displayed on the top of the stack again.

5.2 Basic concepts of taskAffinity

  • Defines the Task that the Activity instance wants to enter;
  • If an Activity does not display the taskAffinity property of the Activity, then this property is equal to the taskAffinity specified by the Application. If the Application does not specify, then the value of the taskAffinity is equal to the package name.

5.3. Commonly used values ​​of IntentFlag

There are many types of IntentFlag, we will only select a few commonly used ones to explain.

5.3.1、FLAG_ACTIVITY_NEW_TASK

The system will find or create a new task to place the target activity. When searching, it will match according to the taskAffinity property of the target activity. If the taskAffinity of a task is found to be the same, the target will be pressed into this task. If the search fails, then Create a new Task and set the taskAffinity value of the Task to the taskAffinity of the target Activity, and place the target Activity in this Task.

5.3.1.1, code demonstration

Method of setting IntentFlag:

Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

The first case \color{red}{the first case} Di Yi Zhong situation situation : FLAG_ACTIVITY_NEW_TASK way to start SecondActivity, but SecondActivity not add taskAffinity property, we look at the results:
effect
you can see, although weFLAG_ACTIVITY_NEW_TASKstart, but the Task Activity where two or the same, which is why ? That's becauseif an Activity does not display the taskAffinity property of the Activity, then this property is equal to the taskAffinity specified by the Application. If the Application does not specify either, then the value of the taskAffinity is equal to the package name. That is to say, at this time, the values ​​of the two taskAffinity values ​​of SecondActivity and MainActivity are both package names, so SecondActivity will definitely be placed in the stack where MainActivity is located.

The second case \color{red}{the second case} First dicarboxylic Species case situation : In a manner FLAG_ACTIVITY_NEW_TASK start SecondActivity, and SecondActivity provided taskAffinity properties:

<activity android:name=".SecondActivity" 
	android:taskAffinity="flag.newIntent.test"/>

Let's take a look at the effect:
Effect two
You can see that SecondActivity and MainActivity are no longer in the same stack at this time.

5.3.2、FLAG_ACTIVITY_SINGLE_TOP

The singleTop in the same four startup modes will not be demonstrated here.

5.3.3、FLAG_ACTIVITY_CLEAR_TOP

The same singleTask in the four startup modes is not demonstrated here.

5.3.4、FLAG_ACTIVITY_REORDER_TO_FRONT

This startup mode means that if an Activity instance already exists in the stack, it will be brought to the top of the stack, a new Activity will not be started, and the Activity instance above it will not be deleted.

5.3.4.1, code demonstration

Let's first look at the effect:

Insert picture description here
we start SecondActivity in MainActivity, then start ThirdActivity in SecondActivity, and then start SecondActivity in ThirdActivity through FLAG_ACTIVITY_REORDER_TO_FRONT. At this time, because there is already an instance of SecondActivity in the stack, we will take this instance. To the top of the stack, and will not destroy all instances on SecondActivity, so the order of Activity instances from the bottom of the stack at this time is MainActivity --> ThirdActivity --> SecondActivity.

Six, summary

This article mainly talks about the five startup methods of Activity, including three display startups and two implicit startups. It also talks about the life cycle of single and multi-Activity, as well as setting the startup mode of Activity through lunchMode in AndroidManifest and through Intent The .setFlag() method sets the startup mode of the Activity.

In the next article, we will explain how to use Intent to pass parameters , use Bundle to pass data , pass complex data, and start system Activity .

For details, see the Activity analysis of the four major components of Android (below)

Guess you like

Origin blog.csdn.net/weixin_38478780/article/details/108739563