In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the Activity life cycle and startup mode example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
As one of the most commonly used components in Android development, Activity is an important content that Android developers must be familiar with and master. At the same time, Activity is also a direction that is often asked in interviews. Therefore, the importance of mastering Activity is self-evident.
Stack is a common data structure, which has the characteristics of first-in-first-out, last-in-first-out. In terms of data form, it can be represented by the following graph:
In this stack, every new data we put into the stack will be placed at the top of the stack, while the other data that has been put in before will be gradually moved to the bottom of the stack in order. it looks as if the data that came in first was pressed down the bottom of the stack by the new data that came in later. This situation is called stack pressing. Like the magazine of a pistol, when we load it, the bullet in the back will be gradually squeezed to the bottom. When we need to take out data, because the stack specifies an entrance and exit, that is, the head of the stack (also called the top of the stack), when we take out the data, we also have to take it out from the top of the stack in the order in which the data comes in, and each time we take out an order, the rest of the data in the stack will forget to move up until the last data is taken out from the top of the stack. This situation is called bullet stack. And if we don't want other data, and the value needs the second-to-last data in the stack, there's no choice but to pop all the data in front of it off the stack before you can get it. Otherwise, everything is out of the question. In the design of Android, the data structure of stack is used to store Activity. It has a name, called task stack, also called fallback stack. About the knowledge of stack, so far basically can be used to introduce Activity, as for other aspects of content, you can refer to other blogs or books. What is recommended here is Cheng Jie's book "data structure of boasting".
What is Activity:
Activity Lifecycle Classic diagrams:
Activity, Chinese "activity". In Ren's book, it is understood as an interface. In fact, I quite agree with this view, because Activity is actually the user interface that we show in the application, it loads the specified layout file to display various UI elements, and sets event handlers for these elements, thus realizing the interaction between the user and the application. For example, when we open a mobile phone App, the login interface, registration interface, main interface and so on are all different Activity. It is the interface operation that the user can directly see with the naked eye on the App, as well as the event handling for some specific actions of the user to the App (this is invisible to the user).
The composition of Activity:
In the above introduction to Activity, a layout file in .xml format is displayed as a visible part of the user, while an Activity object is used to lay out the event handler. So why do we call the part visible to the naked eye Activity? Because we can manipulate the layout file directly in Activity, which means that the layout file is an extension of Activity objects, but in most cases, the way we use Activity is still Activity objects + xml layout files. However, about the composition of Activity, it is not that simple. In fact, a complete Activity composition is not that simple, and there are other levels of encapsulation on top of the view that Activity and developers can set, that is, the scope of layout of the user interface. As shown in the figure:
We can see that there is a PhoneWindow under Activity, and this PhoneWindow is actually an implementation class of a class called Window. Speaking of Window, I believe someone has tried to call such a method when canceling the title bar that comes with Activity:
/ / cancel the title bar requestWindowFeature (Window.FEATURE_NO_TITLE) that comes with the system
And the specific appearance of this method is as follows:
Public final boolean requestWindowFeature (int featureId) {return getWindow () .requestFeature (featureId);}
We find that it actually calls back a getWindow (). RequestFeature (featureId) method, and this getWindow () returns an object of type Window mWindow:
Public Window getWindow () {return mWindow;}
So, when we look at this Window source code, we find that it is actually an abstract class.
Public abstract class Window {/ * Flag for the "options panel" feature. This is enabled by default. * / public static final int FEATURE_OPTIONS_PANEL = 0; / * * Flag for the "no title" feature, turning off the title at the top * of the screen. * / public static final int FEATURE_NO_TITLE = 1; / * * Flag for the progress indicator feature * / public static final int FEATURE_PROGRESS = 2; / * * Flag for having an icon on the left side of the title bar * /.}
We know that for an abstract class to work, it needs a subclass to inherit the abstract class, and PhoneWinsow is such an implementation class. The operation we perform to remove the title bar is actually calling the method in this PhoneWindow. This also reflects from the side that the composition of Activity is more than just an Activity object + xml layout file. Although this is our common pattern, it is actually encapsulated.
Creation, Activation and destruction of Activity
Create Activity
To create an Activity in your code, you need to go through the following steps:
1. Create a new class that inherits from android.app.Activity. It is recommended that the class be named in xxxActivity style, such as LoginActivity
two。 In the AndroidManifest.xml file
< application>Node to use the new
< activity>Node registers the Activity and sets the
< activity>The node configures the android:name property. The value is the package name and class name of the Activity class, and it is recommended for each
< activity>The node configures the android:label attribute. For example:
Note: if there is more than one Activity, each
< activity>Nodes are not prioritized. If you want to adjust the Activity that is the first to enter the software display interface, you need to use the
< activity>The following information is configured in the node:
3. If you need to add a xml layout file to Activity, you need to create and design the layout in the res\ layout directory, naming it activity_xxx (which matches xxxActivity), such as activity_login.
4. After designing the layout file, override the onCreate () method in the Activity class, and load the layout in this method by calling the setContentView () method. For example:
Protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); requestWindowFeature (Window.FEATURE_NO_TITLE); setContentView (R.layout.activity_registe})
The above is the way to create Activity manually, of course, we can also use IDE help to do so. Take Eclipse as an example:
1. Shortcut key: ztrl+N. The pop-up window is as follows:
Select "> Android Activity" under the Android directory, and click Next. The results are as follows:
Select the style, and here you select the default style Black Activity. Click next, and the results are as follows:
Here, change the Activity Name column, and the following Layout column will automatically change, click finish. Created successfully.
Activate Activity
After we have created Activity, it needs to be activated before it can be used unless it is set as the default interface. A new Activity can be activated by calling the startActivity (Intent) method defined by the Activity class, where the parameter Intent object can be created directly through the constructor of the Intent class.
When using the constructor of the Intent class, specify two parameters, the first of which is the Context object
The second parameter is the activated Activity class, such as SecondActivity.class. Examples are as follows:
/ / Jump to another ActivitystartActivity (new Intent (this,SecondActivity.class))
In this way, the operation of activating SecondActivity and jumping to SecondActivity interface is realized.
The above is the first way to activate Activity, and if you need to set it after activating the second Activity and return data to the first Activity after the Activity executes finish, you can use the startActivityForResult () method. The usage is as follows:
Intent mIntent = new Intent (this,SecondActivity.class); int requestCode = 0bot startActivityForResult (mIntent,requestCode)
At the same time, in the first Activity to rewrite the data return processing method onActivityResult (); usage is as follows:
Protected void onActivityResult (int requestCode, int resultCode, Intent data) {}
Note: requestCode can be set freely, but it must be greater than or equal to 0
Destroy Activity
Call the finish () method defined by the Activity class to destroy the current Activity.
Life cycle Analysis of Activity:
Life cycle analysis in typical cases
Under normal circumstances. Activity goes through the following lifecycles, each with a declaration cycle method:
1.onCreate (): we have already touched this method in our previous example of manually creating Activity, which is the first lifecycle method executed by the Activity lifecycle, indicating that the Activity is being created, in which we can perform some initialization work. Such as loading xml layout files, initializing element controls and loading corresponding data or setting listeners.
2.onStart (): indicates that the Activity is starting and gradually becomes invisible until the Activity is displayed to the foreground
3.onRestart (): indicates that Activity is being restarted. Typically, this method is called when the current Activity is restored from an invisible state to a visible state.
4.onResume (): called when Activity is fully displayed in the foreground (fully visible). After executing this method, Activity requests ActivityManagerService (hereinafter referred to as AMS) to render the view it manages, and the Activity is on top of the stack and remains running.
5.onPause (): this method is called during the gradual transition of Activity from a visible state to an invisible state. Usually called when the system is ready to start or restore another Activity. At this point, you can do some operations such as data storage, stop animation or release some consumed CPU resources, but be careful not to do time-consuming operations. Otherwise, it will cause stutter phenomenon or ActiviNotResponding exception (ANR).
6.onStop (): indicates that the Activity is stopped, that is, it is completely invisible.
7.onDestory (): called before the Activity is completely destroyed, indicating that the Activity has been completely removed from the task stack. Is the last declaration cycle method of Activity.
A very clear diagram of the life cycle of Activity has been found on the Internet:
Here are two additions to the special case from onPause ()-> onStop ():
1. As stated in the book, when the new Activity uses a transparent theme, Activity does not call back the onStop () method
two。 When the newly launched Activity is a dialog Activity, the onStop () method is also not called back.
With regard to the two questions raised in the book, combined with the explanation of the Great God and some of his own ideas, it is summarized as follows:
The problems 1:onStart and onResume, onPause and onStop are similar in description. What's the difference to us?
God's explanation: onStart and onStop are callbacks from the point of view of whether the Activity is visible or not. And whether onResume and onPause are located in the foreground from this angle to callback. There are no other obvious differences in actual development.
My idea: onStart and onPause correspond to a dynamic change, the former from invisible gradually visible to fully visible (onResume). The latter is from completely visible gradually invisible to completely invisible state (onStop). Accordingly, onResume and onStop correspond to a static change. Call onResume as soon as it is fully visible, and onStop as soon as it is not visible. This is why the onStop method is not called back when the newly created Activity is a transparent theme. Because from the foreground, that is, the window of the display interface, the Activity has not been removed from the window, it is still visible, but the Activity cannot be controlled.
Question 2: assuming that the current Activity is A, if the user opens a new ActivityB at this time, which will be executed first, the onResume of B or the onPause of A.
Great God's explanation: from the point of view of source code analysis, when we want to start an Activity, the request to start Activity will be processed by Instrumentation, and then it sends a request through Bilder like AMS, while AMS maintains an ActivityStack (task stack) inside the stack, which is responsible for the state synchronization of Activity in the stack. AMS synchronizes the state of Activity through ActivityThread to complete the life cycle call. In the source code of ActivityStack, it is determined that before the new Activity starts, the Activity at the top of the stack should onPause first, and then the realStartActivityLocked method in ActivityStackSupervisor calls the scheduleLauchActivity method to complete the calling process of onCreate, onStart and onResume of the new Activity.
My idea: from the description of the function of the life cycle, when we want to start an ActivityB and in its process from invisible to fully visible, it will inevitably take up the space displayed in the foreground, that is to say, in this process, it will make the ActivityA lose its completely visible state and become partially visible or gradually invisible. At this time, the onPause method of A has been called. When the onResume method of B is called, if B is not a transparent theme or dialog Activity, the onStop of A will also be called. That is, first call onPause of A, and then call onResume of B.
Ps: your own ideas have not been deliberated. If you find anything wrong, you can point it out in the comments below so that you can change it in time.
Life cycle analysis under abnormal circumstances
With regard to life cycle analysis in abnormal situations, the Great God mainly talked about two situations:
1. Resource-related system configuration changes cause Activity to be killed and recreated
When there is a sudden change in the system configuration, you need to kill the current Activity immediately and recreate it, just like when the phone suddenly rotates the screen and needs to reload the Activity that adapts to the screen change. The life cycle of Activity is shown in the figure:
When the Activity is abnormally closed and needs to be restored, the Activity will be completely destroyed first, and its onPause, onStop, and onDestroy methods will all be called. Then start calling the onCreate method again. However, because it is an abnormal shutdown, we do not want to see data loss when restoring Activity. Therefore, before the onStop method of Activity is called, the onSaveInstanceState method is executed to save the data in the Activity, the onRestoreInstanceState method is called in the newly recovered Activity, and the Bundle object saved by calling the onSaveInstanceState method before Activity destruction is passed to the onCreate and onRestoreInstanceState methods as parameters, and the reconstruction is judged by comparing the information between the two methods. If it is determined that it is rebuilt, the previously saved data is taken out and restored, and this process occurs before onStart.
As for the process of data recovery, the workflow is as follows:
1.Activity calls onSaveInstanceState to save data
2.Activity entrusted Window to help preserve the data, as if he had given the pledge to someone he could trust before he died.
3.Window entrusts its top-level container to store data. This container is a ViewGroup, which may be DecorView in Activity.
4. The top-level container notifies its child elements to hold the relevant data.
5. Complete
Note: when the Activity is destroyed normally, the system does not call the onSaveInstanceState method to save the data, but only if the Activity terminates abnormally and has a chance to redisplay it.
two。 Insufficient resource memory caused the low priority Activity to be killed
In this case, the data storage and recovery process is the same as in case 1. But to make a distinction here, when the phone runs out of memory, sometimes we exit the app to the background, and when we open it after a while, we find that it restarts the app instead of restoring it, as scenario 2 said. Because what is involved here is not case 2, in fact, case 2 is for Activity, which means that the Activity in the background of the application is kill. What is mentioned above is that the phone destroys the whole application directly when the whole application is in the background, which is a typical lifecycle scheduling process (see the left side of the diagram).
The priority of Activity is recorded below, that is, when there is insufficient memory, the system will drop some unwanted Activity according to the priority of Activity from low to high kill to release other Activity calls.
1. The foreground Activity, the Activity that is interacting with the user, generally means that the user has the ability to operate on controllable UI elements. For example, there is a response when you click a button. The highest priority.
two。 Visible but not foreground Actiyity, for example, Activity pops up a dialog box, which causes the Activity to be visible, but does not have the ability to operate on the control, and can only interact in the dialog box, followed by priority.
3. Background Activity, the invisible Activity located in the background, has the lowest priority, and the system first cleans up this part of the Activity.
An extension of scenario 1: if you want the system configuration to be changed without re-creating it, we can do so by setting the
< activity>Set the following properties in the node to implement:
Android:configChanges= "orientation"
In this case, the role of android:configChanges is to capture changes in the device and call back the appropriate processing method without restoring the Activity. Of course, there are many attribute values about ConfigChanges, but when we need to define multiple attributes, we can separate them with a | sign, such as:
Android:configChanges= "orientation | keyboardHidden"
For more information about the attribute value of configChages and its meaning, please refer to the following:
Startup mode of Activity:
With regard to the startup mode of Activity, it is time to review our preliminary knowledge-the task stack. In Android, the system uses the task stack to store the Activity created each time, which means that as long as there are repeated calls to the same Activity, we have to create multiple Activity and store them in Activity, which not only wastes storage space, but also makes the fallback mechanism of Activity too rigid, which does not meet the needs of flexible development of Android. As a result, Android encapsulates the function of the task stack and forms four startup modes:
1.standard (standard mode): this is the default startup mode of the system. Every time a new Activity is created, a new Activity instance is generated and placed on the corresponding task stack. It's not much different from the typical stack call data.
2.singleTop (top-of-stack reuse mode, also known as top-only mode): in this mode, if the new Activity already has an Activity instance on the top of the stack, the Activity will not be recreated, but will call back the onNewIntent method to retrieve the current requested information, and the newly created Activity will not be called by the system to onCreate or onStart methods. Note that this pattern is only used when the new Activity is already at the top of the stack. Otherwise, a new Activity will be created and the stack will be pushed.
3.singTask (intra-stack reuse mode, also known as task-only mode): in this mode, as long as the Activity exists in the task stack, when we create the Activity, we will set the Activity in the stack to the top. That is, unless the Activity you want to create is already at the top of the stack, the system will bounce all the Activity above that Activity on the stack until the Activity is at the top of the stack. If the Activity you want to create does not exist in the stack, it will directly create and press the stack.
4.singleInstance (single instance mode): this is an enhanced singleTask mode, which not only has all the features of singTask, but also strengthens that Activity with this mode can only be on a single task stack. That is, if ActivityA is in singleInstance mode, a new task stack will be assigned to it when it starts. Because of the reusability of singleTask, no new Activity is created when you need to create an Activity. Note that because the instance created by the singleInsyance mode is in a separate task stack, when we destroy the Activity, we will clean up the Activity in the task stack where the top Activity is located and then clean up the Activity. For example, the startup sequence of Activity is as follows:
A (top of stack)
B (singleInstance)
C
D (bottom of stack)
So when we press the back key continuously, the order of destruction is A-> C-> D-> B.
The relationship between askAffinity and Activity
When talking about the relationship between the two, we can first declare that in the Android system, there is not only one task stack. Very often, there is a task stack between every due program. In general, the Activity created in this application will be put into the task stack under the same application, and the name of this task stack is the package name of the application. So, is there any special case where the Activity we created will go into other task stacks? If so, which task stack would it jump to? We can give the answer through the TaskAffinity attribute.
Each Activity has a TaskAffinity parameter that identifies the name of the task stack that Activity needs to enter. If we do not set it, it defaults to the package name of the current application, that is, the task stack under the current application. If we set the package name of other applications, then the Activity will be transferred in some specific cases. There are two situations described in the book:
1. When TaskAffinity and singleTask startup modes are paired
If you apply an Activity to load singleTask mode, the Activity first checks to see if there is the same task stack as its taskAffinity. If so, check to see if there is an instantiated Activity on the stack, and if so, destroy the Activity above that Activity and call onNewIntent. If not, the Activity is instantiated and merged into the stack. If the task stack does not exist, a task stack is recreated and placed on the stack.
two。 When TaskAffinity is combined with allowTaskReparenting,
In this case, if the allowTaskReparenting of the Activity is set to true, the Activity goes directly to the background until when the task stack with the same name as TaskAffinity enters the foreground, the Activity is transferred to the task stack and is at the top of the stack.
Examples in the book: first, the application of A, B. When you start an ActivityC of B in A, then press the Home key to return to the desktop and open the B application. At this point you will find that what is displayed is ActivityC.
The method of setting up the startup mode for Activity
1. Specify the startup mode for Activity through AndroidMenifest.xml and add attributes to the appropriate node:
Android:launchMode= "launchName"
The launchName here is any one of the four startup modes, pay attention to English!
two。 Set the flag bit in Intent to specify the startup mode. For example:
Intent intent = new Intent (); intent.setClass (MainActivity.this,SecondActivity.class); intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK); startActivity (intent)
Note: when both methods are applied at the same time, the second method shall prevail.
Matching rules of Intent and IntentFilter in Activity:
In the previous introduction to the activation method of Activity, we have introduced how to use Intent to start an Activity, but there are two ways to start Activity. What we said above is explicit startup, which means you can clearly know what the Activity of Activity's next jump is. (you can see it from the parameter object of Intent). On the other hand, implicit startup, another way to start Activity, is more likely to be achieved through the matching of Intent and IntentFilter. Let's introduce the matching rules of Intent and IntentFilter in Activity.
How to set up 1.IntentFilter
In the AndroidManifest.xml file, find the
< application>In the specified
< activity>Add to the tag, such as:
Joint work of 2.Intent and IntentFilter
The joint work of Intent and IntentFilter is shown as follows: when a developer needs to start an Activity, a developer sends a message to the IntentFilter transmitting each Activity through Intent. If the predefined information of an Activity matches the received Activity, it indicates that the next Activity to be started is the Activity. Because we can not see what the next Activity is directly through the code among developers, but the Activity startup process that is completed through this information matching method is implicit startup.
Filtered information for 3.IntentFilter:
There are mainly three kinds of filtering information in IntentFilter: action, category and data, all of which have corresponding functions. If the message passed by an Intent also matches the filtering information set by IntentFilter, then the target Activity can be started successfully, otherwise it fails. Note, however, that multiple IntentFilter can be set for an Activity, and the Activity can also be turned on as long as one of the sets of IntentFilter matches exactly.
The functions of three kinds of filtering information are described below:
Matching rules of action
The essence of action is a string that describes the name of the action triggered by Intent. We know that a person can have multiple names, and when others are looking for this person, they only need to call him by one of his or her first names. Similarly, in IntentFilter, we can define multiple action, and as long as one action matches the information passed by Intent, the match is considered successful. Note that the system itself has some predefined action, which represents some predefined Activity that can be launched, such as dial-up interface, and these predefined action are centrally placed under android.intent.action, and selected from them when called, such as:
Android.intent.action.SEND
The definition format of action in IntentFilter is as follows:
/ / actionName indicates the action information you need to join
The call format of action in Intent is as follows:
String action= "actionName"; Intent intent = new Intent (action)
Category matching rule
Category and action are essentially the same, but they represent different meanings. Category describes the category information of the target component, indicating what the goal can do, such as in the system predefinition:
CATEGORY_GADGET: indicates that the target Activity can be embedded in other Activity
Of course, we can also make custom settings for it.
The matching rules for category are roughly as follows: if Intent contains category, then no matter how many you have, you need to match the category set by the target Activity in IntentFilter. Even if one of them does not match, the following exception will be reported:
Android.content.ActivityNotFoundException:No Activity found to handle Intent {act=actionName cat= [categoryName]}
The definition format of category in IntentFilter is as follows:
The format of the add category call for category in Intent is as follows:
String category = "categoryName"; intent.addCategory (category)
Data matching rule
The matching rules of data are similar to those of action. If data is defined in IntentFilter, then a matching data must also be defined in Intent, but because the structure of data is different from that of action, there will be some changes.
The composition of data
Data consists of two parts: mimeType and URI. Among them, mimeType refers to the media type, which can represent picture image/jpeg, text text/html, audio audio/mpeg4-generic and video video/*, etc. URI stands for uniform Resource Identifier (Uniform Resource Identifier), which is used to determine the storage path of the required resources. Its structure is as follows:
: / /:: / [| |]
The structure is described as follows:
Scheme:URI mode, such as http, file, etc.
The hostname of host:URI, that is, the IP address of the host where the current resource resides, can be expressed as a domain name, such as www.baidu.com
The port number of the port:URI, such as 80, refers to the window path to get the resource.
Path, pathPrefix, pathPattern: indicates path information
The definition format of data in IntentFilter:
Or:
.
The calling methods of data in Intent are:
Intent.setdata (Uri data); intent.setDataAndNormalize (Uri data); intent.setDataAndType (Uri data, String type); intent.setDataAndType (Uri data, String type); intent.setDataAndTypeAndNormalize (Uri data, String type) Thank you for reading this article carefully. I hope the article "sample Analysis of Activity Lifecycle and Startup Mode" shared by the editor will be helpful to you. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.