Android interviewer: I can't answer these questions. Do you really understand the startup mode of Activity?

introduction

When the interviewer asks you to introduce the activity startup mode, most people can say two sentences about stack-top reuse and in-stack reuse. However, are you sure you really understand the startup mode?

If you can answer the following questions, then you can directly exit the current interface.

Suppose there are the following four activities:

  1. A(standard)
  2. B(singleTop)
  3. C(singleTask)
  4. D(singleInstance)

Their startup sequence is ABCDABCD, please describe the changes in the activity stack.

Interaction-based analysis

Example:
1. After the user clicks the application icon on the main screen to start the application, the first Activity interface pops up: A , and opens the following interfaces  A -> B -> C -> D in turn .
2, then press the home key to return to the main screen, then click on the icon to launch the application again, we will find the pop-up interface or  D  instead of screen  A .
3. When we continuously click the back button, the interface in the application will be displayed in reverse order according to the startup sequence, that is, D -> C -> B -> A -> home screen .

Through this example, we can know that the Android system temporarily saves a set of Activity startup chains for the application and records the startup sequence, which leads to the first concept: tasks .

task

Let me talk about the definition of the task first. Android officials call the above-mentioned series of activities chained to complete certain tasks as  tasks .

We all know that each Activity is an independent interface. It is with the concept of tasks that multiple Activities can be linked to form a complete application.

Can multiple tasks exist at the same time

of course can!

Example: We usually use our mobile phones to switch back and forth between Weibo and WeChat chats. Every time we switch, the system will save the last time we left.

Must the activity in the task come from the same application

of course not!

Example: When we set a user profile picture in social software, there are usually two options: photo and photo album. If you choose to take a photo, you will jump to the camera software, and if you select an album, you will jump to the system photo album software. Through the joint cooperation between these several software, a task was completed.

Root Activity in the task

Under normal circumstances, we start the application by clicking the application icon on the home screen of the device. Similarly, the home screen of the device is also the starting point for most tasks, and the entry activity in the application is the root activity of this task. You must declare the root activity Particularly familiar with:

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

When the user taps the application icon on the home screen to open the application, if the application has not been used recently, a task will be created and the entry Activity in the application will be opened as the root Activity in the task. Otherwise, just call out the task of the application and put it in the foreground.

After understanding the task, we probably know the rules of how the Android system saves the activity state in the above examples.

Return stack

Task is a particularly virtual concept, it is only available for the convenience of developers to understand, and the real storage of Activity in the system is a data structure that follows the principle of first in, last out: stack. It is generally called the return stack (task stack, stack, in fact, it is called anything).

The return stack is the actual carrier of the task, and all the activities in each task will be stored in the corresponding return stack according to their opening order. Therefore, the order of the Android system display interface is to first find the task where the interface is to be displayed, and then find the displayed Activity in the corresponding return stack.

It is worth mentioning that due to the particularity of the storage structure of the return stack, the outside can only access the Activity at the top of the stack, which is the one that is pushed onto the stack last. So if an Activity wants to be displayed on the screen, it must exist at the top of the stack.

Push and pop

When the current activity starts another activity, the new activity will be pushed to the top of the stack and be displayed on the screen as the focus. The previous Activity remains in the stack, but it is in a stopped state.

When the user presses the "Back" button, the current Activity will pop up from the top of the stack (Activity is destroyed), and the previous Activity will resume execution. If the user continues to press "return", the corresponding activity in the stack will pop up to display the previous activity until the user returns to the home screen (or return to any activity that was running when the task started). When all the activities are removed from the stack, the task ceases to exist. The stack will also be recycled.

Special task

Through the previous understanding, we know that if you want to open a new interface, you need to put the Activity instance on the top of the return stack corresponding to the current task. This operation is regardless of whether the Activity has been instantiated before or whether it already exists in the stack.

However, in some special circumstances, we will find some "exceptions".

Example 1: When an application from multiple different tasks chooses to use the system browser to access web pages, the browser application does not create an Activity in the return stack of each task, but displays all web pages in the form of tabs Shown in the same interface.

In this example, the activity of the browser application will not be recreated if it has been instantiated.

Example 2: Xiao Ming shared a piece of Weibo content with you in WeChat. After you opened it, you jumped to the Weibo detail page in the Weibo APP. When you finish reading the content, press the return key to exit the interface and find that it is not a return. When I arrived at the WeChat chat interface, I came to the Weibo homepage (or the last time I stayed in Weibo).

In this example, although the Activity of the Weibo details page is started by the task of the WeChat application, it is not added to the task of the WeChat application, but is added to the task stack of the Weibo.

Management tasks

Obviously the above two examples are not uncommon in actual use. For this special situation we need targeted management tasks, and the well-known startup mode is only one of them.

Define start mode

Defining the startup mode of Activity is actually defining how (whether) a new instance of Activity is associated with the current task. How to enter the current (or other) task.

If you only say that there are four startup modes for Activity, it is actually inaccurate, because we can define different startup modes in two ways:

  • Use the definition in AndroidManifest.xml
    在AndroidManifest.xml中<activity>标签下使用lauchMode属性来指定当前这个activity的启动模式。

  • Use Intent flag definition
    在调用startActivity(Intent intent)前,通过调用intent.addFlags()或者intent.setFlags()方法为Intent添加一个标志,用于为将要启动的Activity声明启动模式。

What is the difference between the two?

Both of the above two methods can declare the startup mode for the activity, but the usage scenarios are different.

  1. If we want an activity to perform a special startup mode under any circumstances, we can use the method declaration of AndroidManifest.xml.

  2. If we want an activity to start normally in most cases, but in a few cases to execute a special startup mode, we can add a flag statement in the Intent when we need to execute a special startup mode.

  3. If an activity is declared in both ways, the way to use the Intent flag has a higher priority than AndroidManifest.xml.

  4. Some of the startup modes defined in the two methods are different. Some startup modes defined in the Intent flag are not in AndroidManifest.xml, and vice versa.

  5. The four startup modes we often talk about are actually those defined in AndroidManifest.xml.

Use AndroidManifest.xml to declare the startup mode

When declaring the Activity in the manifest file, you can use <activity>the][ launchModeattribute of the element to specify how the Activity should be associated with the task.

launchMode There are four startup modes that you can assign to  attributes:

  • standard
  • singleTop
  • singleTask
  • singleInstance

Regardless of their specific operations, we must first know that these four startup modes can be divided into two categories:

  • standardAnd singleTop
    the activity of this type of startup mode can be instantiated multiple times, their instances can be placed in any task, and can be located anywhere on the return stack.
  • singleTaskAnd for activities singleInstance
    with this type of startup mode, they can only have one instance, and the instance can only exist in a single task.

standard: standard mode

The default startup mode, when starting an activity, directly create a new instance and push it to the top of the task stack that started it.

singleTop: stack top multiplexing mode

The only standarddifference in this mode is that if singleTopan instance of this activity already exists on the top of the stack of the current task when the activity in the mode is started , then a new instance will not be created, but the method of the instance will be called onNewIntent(). Others are the same as the standard mode.

singleTask: In-stack reuse mode

This mode is a bit special, we first introduce it according to the usage scenario, when we are about to start the activity of this mode, the system will judge whether there is currently the task stack it wants:

  1. No task stack it wants
    系统会新创建一个任务,并将该activity实例化作为该任务的根activity。

  2. Has the task stack it needs
    这时候系统会找到该任务栈,如果任务栈里只有它自己则直接调用该activity实例的onNewIntent()方法。如果任务栈中它的上方还存在别的activity,那么这些activity会被全部弹出栈。

As for what is "the task stack it wants", we will analyze it separately below.

singleInstance: Singleton mode
is basically the singleTasksame, it will create a separate task for the activity and can be reused. However, the activity in this mode does not allow other activities to exist in the same task as itself, and any activity started by this activity will be opened in other tasks.

Use the Intent flag to declare the startup mode

In this way, you can add a flag to the Intent by calling intent.addFlags(int flags)or intent.setFlags(int flags)method to declare the startup mode for the Activity to be started.

Before starting the introduction, some literacy science should be done:

  1. A Intent can set up multiple signs, which is why there are addflags()and setFlags()two methods of why.
  2. The parameters that set the flag for the Intent are static constants of the Intent class.
  3. Setting the Intent flag is not only the function of setting the activity startup mode, but also setting different parameters and other functions.
  4. There are many logos that can operate the activity startup mode in the Intent logo. We only introduce the three typical ones.

Intent.FLAG_ACTIVITY_SINGLE_TOP The startup mode in the
same AndroidManifest.xmlway singleTop.

Intent.FLAG_ACTIVITY_NEW_TASK is the startup mode in the
same AndroidManifest.xmlway singleTask.

Intent.FLAG_ACTIVITY_CLEAR_TOP
If the activity to be started already exists in the current task stack, it will pop up and destroy all the activities above it, and call the onNewIntent()method of the activity instance instead of starting a new instance of the Activity.

It is singleTaska bit like but not the same, there AndroidManifest.xmlis no corresponding value in the method.

singleTaskFLAG_ACTIVITY_CLEAR_TOPFunctions included by default .

Related tasks

In the analysis singleTask, it was mentioned that before starting the activity in this mode, it will look for the "task stack it wants", so how to find it? This leads to the attributes under the AndroidManifest.xmlmiddle <activity>tag taskAffinity.

taskAffinity attribute

taskAffinity attribute scientific name task relevance, to put it bluntly, this parameter can specify the name of the task stack to which the current activity belongs, and the value of this attribute is a string:

Example:android:taskAffinity="com.test.demo.task1"

If you <activity>don't specify this attribute in the tag, then it will use <application>the taskAffinityattribute of the <application>tag . If it is not specified under the tag, it will use the package name as the default value.

taskAffinity 与 singleTask

After knowing the taskAffinityproperties, we are reorganizing the singleTaskstartup mode.

  • If we specify the taskAffinityvalue of the attribute, then just like the previous analysis, create a new task, etc...
  • If we do not specify taskAffinitythe value of the attribute, the new activity is the taskAffinitysame as the attribute value of the current task , so the instance of the new activity will be placed in the current task stack.

Except for singleTask?
Now that we know that the taskAffinityattribute can forcefully specify the task stack to which the activity belongs, what does this attribute look like in other startup modes? Many people on the Internet say that there is no effect. I didn’t believe it, so I tested it myself and came to the following conclusions:

  1. When I first introduced  SingleInstanceit, it said that it singleTaskwill create a new task like the same. Since it singleTaskis based on the taskAffinityattribute to determine whether to create a new task, do you singleInstancealso need to specify this attribute?
    The answer is no! As long as the startup mode is for singleInstanceit, a task will be opened separately.

  2. SingleToptaskAffinityAfter the attribute value is specified in the mode , he will magically switch to the specified task stack, except that it is the same as before.

  3. The most amazing thing is Standardthat it is also affected by the taskAffinityproperties, and it will switch to the specified task stack, but when we start this activity multiple times, it will not create instances multiple times, but pull up the previous For the started instance, what is more special is that the other three startup modes will call the onNewIntent()method when the previous instance is reused , but it will not call the method.

Other functions of taskAffinity

Another function of taskAffinity is that it can redirect the task, which means that this activity originally belonged to task A. When a task B with the same value of the taskAffinity attribute of the activity is created, the activity will be transferred from task A. Go to task B.

To achieve this function, we also need allowTaskReparentingthe cooperation of attributes:

  1. We taskAffinity="A"add attributes under the activity tag given in the manifest file android:allowTaskReparenting=true.
  2. In taskAffinity="B"starting the next task activity, then this activity is present in the task B, respectively.
  3. When taskAffinity="A"the task is created or placed in the foreground, the activity will be transferred to its task stack, located at the top of the stack.

Cleanup task

If the user leaves the task for a long time, the system will clear all activity tasks, except for the root activity. When the user returns to the task again, only the root Activity is restored. The reason for the system to do this is that after a long period of time, the user may have given up the operation performed before, and return to the task to start a new operation.

You can modify this behavior using the following Activity properties:

alwaysRetainTaskState
If this property is set to "true" in the root Activity of the task, the default behavior just described will not occur. Even after a long period of time, the task still keeps all activities in its stack.

clearTaskOnLaunch
If this property is set to "true" in the root Activity of the task, then whenever the user leaves the task and returns, the system will clear the stack to only the root Activity. Even if you only leave the task for a while, the user will always return to the initial state of the task.

finishOnTaskLaunch is
similar to clearTaskOnLaunch, but is more ruthless. When the user leaves the task and comes back, the activity of the entire task will be cleared, even the root activity, which is equivalent to starting the task for the first time.

Practical application of startup mode

I personally feel that the four common startup modes are singleTopnot well understood, and the others are fine.

singleTop

singleTopThe activity feature of the mode is that in addition to externally starting it to display information, it can also start itself to update the display information in the same way, which reduces redundant codes and reduces maintenance costs.

Example: If you are asked to design an APP with a search application, the homepage has a search box, enter information and click the search button to enter the results page to display the results. For the convenience of users, the results page also has a search box, which has the same function as the search box on the homepage , How would you design?

singleTask

This startup mode can be divided into two situations:

  1. TaskAffinity is not specified.
    At this time, the activity can be used as the entrance of a module in the application

The startup process is as follows: WeChat homepage >> chat page >> chat settings page >> user profile page >> chat page. At this time, we press the back button to return directly to the WeChat home page.


  1. If taskAffinity is specified, if a new task is opened using this startup mode, two applications will be opened in the user’s perspective (two recent applications will be seen in the task manager), so use it with caution, I can think of the usage Just a Word application opened two documents.

singleInstance

In this case, no matter how many tasks start it, it will exist as a single task. This mode is extremely special and should be used with caution.

Example: dial interface, alarm clock interface.

Interview review route

I won’t talk about the extra words. Next, I will share a review route for the interview. If you are also preparing for an interview but do not know how to review efficiently, you can refer to my review route. If you have any questions, please feel free to communicate with each other. Come on!

Here is a direction for everyone to learn systematically:

1. Watch the video for systematic learning

The experience of Crud in the past few years has made me realize that I am really a fighter in the rookie. It is also because of Crud that my technology is relatively fragmented and not deep enough to be systematic, so it is necessary to study again. What I lack is system knowledge, poor structural framework and ideas, so learning through videos is better and more comprehensive. Regarding video learning, individuals can recommend to study at station B. There are many learning videos on station B. The only drawback is that they are free and easily outdated.

In addition, I have collected several sets of videos myself, and I can share them with you if necessary.

2. To systematically sort out knowledge and improve reserves

There are so many knowledge points in client development, and there are still so little things in the interview. Therefore, there are no other tricks for the interview, just to see how well you prepare for these knowledge points. So, when you go out for an interview, it is good to see which stage you have reached in your review.

System learning direction:

  • Essential skills for architects: in-depth Java generics + annotations in simple language + concurrent programming + data transmission and serialization + Java virtual machine principle + reflection and class loading + dynamic proxy + efficient IO

  • Android advanced UI and FrameWork source code: advanced UI promotion + Framework kernel analysis + Android component kernel + data persistence

  • 360° overall performance tuning: design ideas and code quality optimization + program performance optimization + development efficiency optimization

  • Interpretation of open source framework design ideas: hot repair design + plug-in framework interpretation + component framework design + image loading framework + network access framework design + RXJava responsive programming framework design + IOC architecture design + Android architecture component Jetpack

  • NDK module development: NDK basic knowledge system + underlying image processing + audio and video development

  • WeChat Mini Program: Mini Program Introduction + UI Development + API Operation + WeChat Docking

  • Hybrid development and Flutter: Html5 project combat + Flutter advanced

After the knowledge is sorted out, it is necessary to check and fill in the vacancies. Therefore, for these knowledge points, I have prepared a lot of e-books and notes on hand. These notes provide a perfect summary of each knowledge point.

3. Read the source code, read the actual combat notes, and learn the ideas of God

"Programming language is the way the programmer expresses, and the architecture is the programmer's perception of the world." Therefore, if programmers want to quickly understand and learn the architecture, reading the source code is essential. Reading the source code is to solve problems + understand things, and more importantly: see the ideas behind the source code; programmers say: read thousands of lines of source code, and practice thousands of ways.

Mainly include WeChat MMKV source code, AsyncTask source code, Volley source code, Retrofit source code, OkHttp source code, etc.

4. On the eve of the interview, sprint questions

Within a week before the interview, you can start sprinting. Please keep in mind that when brushing the questions, the technology is the first priority, and the algorithm is basic, such as sorting, etc., and the intellectual questions are generally not asked unless they are school recruits.

Regarding the interview questions, I personally prepared a set of systematic interview questions to help you learn from one another:

The above content is free to share with everyone, friends who need the full version, click here to see all the content .

Guess you like

Origin blog.csdn.net/weixin_44339238/article/details/111396988