Hi, Hello, everyone. We met again. In the last issue, we talked about how to install as. Are there any partners who can’t wait to create their own projects and start to try them? So in this issue, we mainly introduce activities. As one of the four components of Android, activity plays a very important role. This article will focus on Android’s life cycle, startup mode, basic configuration and other aspects.
Every interface of an application is an activity, so it is also called a view interface. To understand from the literal meaning, activity has the meaning of activity. The operations we carry out in the application are all concentrated on the activity, such as dialing, taking photos, sending email and looking at maps. Each activity is set to a window on which an interactive interface can be drawn An application is usually composed of multiple activities, which are usually loosely coupled. Generally, an application contains a main activity, that is, the activity that first enters when clicking the desktop icon.
Android creation and startup
To create and use a simple activity:
After the new project of androd studio is completed, a java file will be created automatically. This file is activity, because it inherits the activity provided by the system framework layer. Here appcompatactivity is a subclass of activity, and our mainactivity indirectly inherits activity.
And you will see that mainactivity forces the oncreate method to be overridden. In oncreate, set our custom page layout file for activity through setcontentview.
Register activity in manifest
The activity must be registered in Android manifest.xml. If the activity is not registered, it cannot operate normally. In fact, when using the four major components (activity, service, broadcast receiver, ContentProvider) in Android, it needs to be registered in Android manifest.xml. In the XML registration information above, whereDesignated in
Indicates that this activity is the main activity. Click the application icon in Android system to enter the main activity first.
Activity is used to start, stop and transfer activities among applications through intent.
There are three ways to start an activity:
1. Display start
Register the second activity — secondactivity here, and remember the previous registration operation. We register secondactivity in the manifest file. Now you can start secondactivity in mainactivity.
Intent intent = new Intent(this, SecondActivity.class); //Create the intent object through the class object of the context context and secondactivity.java class Startactivity (intent); // call the method provided by the system framework layer to start secondactivity.
2. Implicit start
If secondactivity configures the action, category and data of the intent filter in the androidmanifest.xml file, as follows:
You can start secondactivity as follows:
Intent intent = new Intent("myaction2"); startActivity(intent);
3. Default startup
Click the application icon through the desktop icon to enter the first activity of the program. Because its startup mode is different from the above two modes, it is divided into the third type of startup mode If the activity is in the action and category of the intent filter in the androidmanifest.xml file, it is as follows:
Then, click the application icon on the desktop to start the activity.
Note: if the above action and category are configured in all n activities, there will be icons of N applications on the desktop. Click different icons to enter the corresponding activities.
Life cycle of activity
The life cycle of activity is as follows:
Indicates that the activity is being created. This is the first method to execute. It is only executed once in the life cycle of the activity. Do some initialization work in this method, such as calling setcontentview to load the interface layout, initializing the data required by the activity, etc. Subsequent calls to onstart().
Indicates that the activity is restarting. Generally, onrestart will be called when the current activity changes from invisible state to visible state. This situation is usually caused by user operations. For example, when the user presses the home key to return to the desktop or opens a new activity, the activity will be suspended, and then the user will return to the activity. Subsequent calls to onstart().
Indicates that the activity is being started and about to start. At this time, the activity is visible, but it hasn’t appeared in the foreground, so it can’t interact with users. At this time, it can be understood that activity has been displayed, but we haven’t seen it yet. The next method is onresume().
It indicates that the activity is visible, has appeared in the foreground and started activities, and can interact with the user normally. It should be noted that the difference between OnStart and onresume is that both activities are visible, but the activity is still in the background at OnStart, while the activity is in the foreground at onresume. At this time, you can turn on the animation or get exclusive device operations, such as turning on the camera, getting the microphone, etc.
Indicates that the activity is transferred from the foreground to the background. Normally, onstop will be called immediately. It’s still visible. If you quickly return to the current activity at this time, onresume will be called, which is an extreme case, and it is difficult for user operations to reproduce this scenario. At this time, you can do some operations such as storing data, stopping animation, etc., but note that it cannot be too time-consuming. If it is too time-consuming, it will affect the display of new activities. Onpause is executed first, and the oncreate of the new activity will be executed. Onresume corresponds to onpause.
Indicates that the activity is about to stop, and the current activity is not visible to the user. You can do a little heavy recycling. Subsequent operations may be onrestart or ondestroy or keep this status.
Indicates that the activity is being destroyed, which is the last callback in the life cycle and only called once. The condition is that the activity itself has been executed, or the system is low on resources and needs to recycle resources to destroy the activity.
We consider the following situations: 1. When a toast pops up, will a callback occur No 2. When an alertdialog pops up, will a callback occur? No, if the alertdialog gets the focus, the activity will trigger the onwindowfocuschanged callback 3. When a popwindow pops up, will the callback occur No, if popwindow gets focus, such as popupwindow.setfocusable (true), activity will trigger the onwindowfocuschanged callback 4. When the horizontal and vertical screens are switched, the activity will be destroyed and recreated. If only the onconfigurationchanged() callback is triggered when the activity is configured with Android: configchanges = “orientation”, the activity will not be recreated.
There are four startup modes of activity, different modes. Corresponding to the creation and reuse policy of the activity object, you can specify the startup mode of the activity in the manifest and code.
Before exploring what startup mode is, ask a few questions:
Principle of startup mode (what is task stack)?
Why do I need boot mode?
What are the characteristics of four task stacks?
What is task stack
Android task stack, also known as task, is a stack type data structure: first in, first out. It is used to store our activity components.
Each time a new activity is opened or an activity is exited, an activity will be added or decreased in the structure of the task stack, which contains an activity collection. Android system can manage each activity orderly through task, and decide which activity to interact with the user: only the activity at the top of the stack can interact with the user.
When the application exits, the activity stack in all task stacks must be cleared before the task stack can be destroyed. Of course, the task stack can be moved to the background and the status of each activity can be saved. The user can be listed the activity tasks in an orderly manner without losing the activity information.
There may be more than one task stack in an application. In the case of a certain system, a single activity can enjoy a task stack, and there will be activities in a task stack that can come from different apps. Activities in the same app may be in different task stacks.
Why startup mode is needed
In the process of application development, you generally need to jump between multiple activity components, or you may need to open reusable activities of other applications in this application. In the development process, we need to jump to the original activity instance that has been opened. At this time, we hope that this activity can be reused instead of re creating a new activity instance,But according to the default behavior of Android system, a new activity instance object will be created for us every time and added to the task stack, and the data and information status of activity will be preserved 。
We can add a button in mainactivity, click the button to jump to secondactivity, then add two buttons in secondactivity, click a button to jump to mainactivity, and add the following code in the click event of another button:
//Get activitymanger ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); //Get task stack may be multiple List runningTasks = am.getRunningTasks(5); //Get the current task stack ActivityManager.RunningTaskInfo runningTaskInfo = runningTasks.get(0); //Gets the number of activities in the current task stack, that is, the number of activity instances that are not currently replaced. int numRunning = runningTaskInfo.numRunning; //Log print information Log.e("SecondActivity", "numRunning" + numRunning);
The above code does not need to be studied. The main purpose is to show the number of activity instances in the current task stack by default. When we click the button in the main activity to jump to the second activity, when we jump to the second activity, click the first button to jump to the main activity, and repeat this operation. Finally, click the first button to get the number of activities in the current task stack. The following is the result of the method and its corresponding runtime.
This causes data redundancy, too much duplicate data, and may eventually lead to memory overflow (OOM). To solve these problems, Android system provides a set of activity startup mode to modify the default activity startup mode.
Characteristics of four task stacks
Standard mode (general mode)
In the system default mode, every time an activity is started, a new instance will be created, regardless of whether an instance has been created by the activity.
Singtop (stack top multiplexing mode)
In the stack top reuse mode, when the system starts, the system will start whether the current stack top activity is the activity to be started. If it is, it does not need to create a new activity but directly references the activity. If it is not, it will create a new activity. The system will call back the method of activity’s onnewintent().
Singtask (in stack reuse mode)
In the stack reuse mode, if an activity instance already exists in the stack, then the activity will not be recreated. At the same time, the onnewintent() method of the activity will be called back, and the activity instance will be placed on the top of the stack, and the activity instance that was originally at the top of the instance will be destroyed. If another program starts activity, it recreates a task stack.
Singleinstance (single instance mode)
Single instance mode is an enhanced version of single task, which has all the characteristics of single task. In this mode, activity has only one instance, and can only exist in one task stack.
There are generally two startup modes:
Find the location where the activity is declared in Android manuals.xml. In the activity XML attribute Android: launchmode = “standard”, declare other modes (single top, single task, single instance).
When you jump to activity in your code, use intent to specify the flag flag bit to use the startup mode. The sample code is as follows:
Intent intent = new Intent(this, SecondActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//Flag startActivity(intent);
Setflags method description
//Use a new task to start activities, but each activity will be in a new task. Intent.FLAG_ACTIVITY_NEW_TASK //Use singletop mode to start an activity. Intent.FLAG_ACTIVITY_SINGLE_TOP //Use the single task mode to start an activity. Intent.FLAG_ACTIVITY_CLEAR_TOP //Use the single task mode to start an activity. Use this mode to start an activity. When an activity starts another activity, the activity will be destroyed without being pushed into the stack. Intent.FLAG_ACTIVITY_NO_HISTORY //Mode cannot specify singleinstance mode, singleinstances can only be declared in Android manifest.xml. Intent.setFlags
Common use scenarios
Here are some common business scenario pages in development that use the page start mode:
As one of the four major components of Android, it is also the most commonly used in the development process of the project. Young people need to understand it deeply and apply it flexibly to the project. Of course, these are the most basic questions that will be asked in the interview.
PS: if you have any unreadable partners, welcome to wxgzh:Look at flowers in next yardThere are all kinds of gods in it to answer the questions that little friends encounter~