Activity as a platitude topic, it is we just contact Android development encountered, although there has been a period of development experience, but when it comes to fully understand the Activity related, I dare not speak nonsense, so combined with personal understanding and book reference, briefly summarize the basic knowledge of Activity. There are some interesting questions left.
The general brain map is as follows (too much startup process is involved, so it is temporarily put in the later stage) :
Activity Lifecycle
I’m not going to explain the basic lifecycle methods here, but that’s what you started with.
Interesting questions
-
Is there any real difference between onStart and onResume, onPuse and onStop?
In practice, they do look similar, but onStart and onStop are called back and forth from Activity visibility, and onResume and onPause are called back and forth from Actvity foreground, In practice there is no other difference.
-
Assuming the current Activity is A, if the user starts A new Activity B, which of B’s onResume and A’s onPuase will be executed first?
The onPause of A is executed first.
In Android’s official documentation, a new Activity can only resume onPause after the old one has finished executing, so we should try to avoid doing too many time-consuming actions in onPause and put them in onStop instead.
Life cycle and handling of exceptions
In our development, we often encounter the problem of screen rotation, which generally leads to the re-creation of the Activity. Therefore, when most developers develop the Activity, the screen rotation is prohibited by default, but in some short video software, screen rotation is very common. So how to deal with the corresponding data preservation and recovery is what we must pay attention to.
Life cycle diagram of an Activity exception
When the system configuration changes, the Activity is destroyed. Its onPause, onStop, and onDestory are called, and since the Activity was terminated under an exception, The system calls onSaveInstanceState to save the state of the current Activity. This method is called before onStop and does not have a sequential relationship with onPause. It may be called before or after onPause. Note, however, that this method only occurs when the Activity is terminated abnormally. This method is not normally called back.
When Actiivty is recreated, It’s going to call onRestoreInstanceState, And pass the Bundle object saved by the onSaveInstanceState method as a parameter to both onRestoreInstanceSate and onCreate. So we can use the onRestoreInstanceState and onCreate methods to determine if the Activity has been rebuilt. If it has been rebuilt, then we can remove the previously saved data and restore it. In terms of timing, OnRestoreInstanceState is called after onStart.
OnSaveInstanceState and ViewModel
The onSaveInstanceState method is called when the Activity is rebuilt due to an exception. However, it should be noted that onSaveInstanceState is not suitable for storing large amounts of data. Google’s recommendation is to use it to store the corresponding ID and key, and the corresponding large amount of data is recommended to use the ViewModel to save.
Now that I’m using the ViewModel to save, soonSaveInstanceStateWhat else does it mean?
-
OnSaveInstanceState is used to save callbacks to application processes terminated due to memory limitations or configuration changes in the background. Its default implementation is to save temporary information about the activity’s view-level state, such as the text entered in the EditText, Rv,Lv slide position, etc. It supports only bundles, so it is not suitable for storing large amounts of data. It is suitable for small amounts of temporary data.
-
The ViewModel can be used as a proxy for loading complex data or as a temporary storage location, but it does not persist in the process of manual Finish. It is more about preserving data when system state changes than preserving UI state.
The startup mode of the Activity
Why does an Activity need a launch mode?
By default, when we start the same Activity multiple times, the system creates multiple instances and places them on the task stack on a last-in, first-out basis. Task stack is a lifO stack structure. An Activity is destroyed each time it returns. So, in order to better manage the Activity and to use the Activity, Android provides startup mode to solve this problem, respectively, for standard, SingleTop, singleTask, SingleInstance
standard
Standard mode, also the default mode. That is, each time an Activity is started, a new instance is created, regardless of whether the instance exists. The corresponding lifecycle also follows the standard lifecycle process.
singleTop
Top of stack reuse mode. If a new Activity is started in this mode and the Activity is already at the top of the current task stack, it will not be created again and its onNewIntent() method will be called when the startActivity jump is called. With this method we can retrieve the information currently requested. Note that the start mode is ignored if the startActivityForResult jump is used.
singleTask
In-stack reuse pattern. This is a single-instance mode, in which no instance is created for the Activity as long as it exists in a stack. As with singleTop, onNewIntent is called back. When an Activity whose startup mode is “singleTask” is started, the system will look for the existence of the Activity in the stack. If it is found, all the activities at the top of the Activity will be removed from the stack. Push it to the top of the stack and call its onNewIntent method. If the Activity does not exist, it is created and pushed to the top of the stack.
singleInstance
Single instance mode, also known as enhanced singTask mode. In addition to all the features of singleTask, it has the additional feature that activities with this launch mode can only be placed in a singleTask stack.
Activtiy of Flags
There are a number of Flags for your Activity that can be used to set the startup mode of your Activity. For example, FLAG_ACTIVITY_NEW_TASK is added when you start an Activity with Application.
FLAG_ACTIVITY_NEW_TASK
Specify the singleTask startup mode for the Activity. Question: Why does Application call startActivity need this tag?
FLAG_ACTIVITY_SINGLE_TOP
Specify the singleTop startup mode for the Activity
FLAG_ACTIVITY_CLEAR_TOP
Destroy the target Actiivty and all activities on it and recreate it. If used with FLAG_ACTIVITY_SINGLE_TOP, all activities above it are destroyed; if the target instance exists, it is not destroyed and its onNewIntent method is called.
FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
With the Activity of the symbol will not appear in the Activity history list, equivalent to specify the properties of the Activity in XML android: excludeFromRecents = “true”.
Note that if this parameter is placed in the first Activity, all subsequent activities in the Activity stack will be affected.
Matching rule of IntentFilter
There are two ways to start an Activity, explicit and implicit. In daily development, explicit is the most commonly used, and implicit is often used as h5 to open an app, or call a system setting page, or open the camera, etc. Implicit invocation is a bit more complicated than explicit invocation. It requires the Intent to match the filtering information set in the target IntentFilter. If the Intent does not match, the target Activity will not start. IntentFilter filter information includes Action,category, and data
Action matching rule
An action is a string. The system has predefined actions, but we can also define our own actions. The matching rule for an action is that the action in the Intent must match the action in the filter. You can define multiple filtering rules, as long as the action in the Intent matches any one of the filtering rules. If your Intent does not define an action, the match fails.
<action android:name="android.intent.action.VIEW" />
Copy the code
Common actions are as follows:
- ACTION_MAIN android. Intent. Action. The MAIN application entry
- ACTION_VIEW android. Intent. Action. The VIEW displaying data to the user
- ACTION_ATTACH_DATA android. Intent. Action. ATTACH_DATA specifies additional information to some other parts of the data
- ACTION_EDIT android. Intent. Action. EDIT display editable data
- ACTION_PICK android. Intent. Action. PICK to select data
- ACTION_CHOOSER android. Intent. Action. The CHOOSER shows an Activity selector
- ACTION_DIAL android. Intent. Action. Call GET_CONTENT display panel
- ACITON_CALL android. Intent. Action. DIAL direct call
- ACTION_SEND android. Intent. Action. SEND text messages directly
- ACTION_SENDTO android. Intent. Action. SENDTO choose texting
- ANSWER the telephone ACTION_ANSWER android. Intent. Action. The ANSWER
Category matching rule
A category is a string, and the system predefines a category for us. For a defined matching rule, the categoty that exists in the Intent must all match the defined rule. System will be the DEFAULT for us to bring android. Intent. The category, the DEFAULT, this and there are some difference between the action.
<category android:name="android.intent.category.DEFAULT" />
Copy the code
Data matching rule
The matching rules for data are similar to those for actions. If a matching rule is defined, the Intent must contain the corresponding data.
<data
android:host="*"
android:mimeType="string"
android:path="/test"
android:pathPattern="*"
android:pathPrefix="/petterp"
android:port="1080"
android:scheme="http" />
Copy the code
Data consists of two parts,mimeType and URI. MimeType refers to media types, such as image/ JPEG. Audio/ MPEG4-genric and video/*, which can represent different media forms such as books, texts and videos. Uris contain more data.
The Uri structure is as follows:
<scheme>://<host>:<port>/[<path>|<pathPrefix>|<pathPattern>]
Copy the code
- Scheme: The URI mode, such as HTTP,file,content, etc., if Scheme is not specified in the URI. Then the other parameters of the entire URI are invalid, which also means that the URI is invalid.
- Host: indicates the Host name of the URI, for example, www.baidu.com. If host is not specified, the other parameters in the entire Uri are invalid, which also means that the Uri is invalid.
- Port: Port number in the URI, such as 80. The port parameter is only meaningful if scheme and host parameters are specified in the URI. The Path,pathPattern, and pathPrefix parameters indicate Path information.
- Path indicates complete path information.
- The pathPattern also represents complete path information, but it can contain wildcard characters ***** and ***** for zero or more arbitrary characters. Note that, due to regular expression specifications, if you want to represent a real string, ***** should be written as \\* and \\\
- PathPrefix indicates the pathPrefix.
Data matching rules
The matching rules for data are similar to those for actions. The Intent must contain data. In addition, data can exactly match one of the data in the filtering rule. In this case, full match means that the data part of the filtering rule also appears in the data in the Intent.
The matching rules are as follows:
<intent-filter>
<action android:name="petterp.test1" />
<data android:mimeType="image/*" />
</intent-filter>
Copy the code
The mineType attribute in the Intent must be image/*. In this case, the filter does not specify a URI, but it does have a default value. The default URI values are Content and file. That is, the URI part of the Intent must be content or file in order to match, even though no URI is specified.
So if we were to call it, we could write something like this:
val intent=Intent("petterp.test1")
intent.setDataAndType("file://abc","iamge/*")
Copy the code
Now, let’s look at another case, which is a little bit more complicated
<intent-filter>
<action android:name="petterp.test2" />
<category android:name="android.intent.category.DEFAULT" />
<data
android:host="www.baidu.com"
android:mimeType="image/*"
android:path="/test"
android:port="8080"
android:scheme="https"
android:pathPattern=". *"/>
</intent-filter>
Copy the code
For this case, we must use the following format when calling:
val intent = Intent("petterp.test2")
intent.setDataAndType(Uri.parse("Https://www.baidu.com:8080/test/ path literally"),"image/*")
Copy the code
If you don’t understand it here, just look at the data matching rules again.
Note: Category must be added, even if it is not included in an Intent(the DEFAULT category is included in an Intent). Otherwise, the corresponding Activity will not be found, because actions that do not contain the DEFAULT category will not receive the Intent.
I’m glad you can see it here. Although this is just the basics of Activity, it is the most basic thing every developer should know. Encourage forward
Refer to the information
- Exploring the Art of Android Development
- Google developers say