This is the 22nd day of my participation in the August Wen Challenge.More challenges in August
1. Activity lifecycle
Activity is one of the four components of Android, arguably the most important of the four components. It is responsible for the display of our interface. In practice, we use setContentView(r.layout.id) to set the display view of the interface. In the Android project structure design, Activity is equivalent to the View layer in the MVC design pattern. In the design of the four major components of Android, in order to facilitate the development and use of developers, Android developers of the four components through the life cycle management, we only need to inherit the Activity to rewrite the life cycle to manage and rational use of Activity.
Let’s take a look at the Activity lifecycle diagram provided in the Official Android documentation:
As you can see from this diagram, there are six main threads in the Activity life cycle: onCreate() — >onStart() — >onResume() — >onPause() — >onStop() — >onDestroy(). Here’s a look at the six life cycle approaches. To create an Activity, we must create a subclass of the Activity. In our custom subclass, we need to implement these callback methods, such as create, Stop, Resume, destroy for the Activity. Brief introduction of the method:
- The onCreate () method
This method must be implemented, and the system calls it when we create an activity. Importantly, we must set the activity’s display view with setContentView(). (Not visible)
- The onStart () method
Called after we’ve created the view, before we show it to the user. Then call the onResume method. (Not visible)
- OnResume () method:
The onResume method is an activity in a visible state that can interact with the user. (Visible available)
- OnPause () method
The system calls this method when we leave the activity. Note: This does not mean that the activity is destroyed. Pause state, remember when playing games, press pause, the game interface will stop motionless, belongs to the visible state, but can not be used, in fact, the principle is basically similar. (Visible but not available)
- OnStop () method
Stopped state: When an activity is completely overwritten by another activity, it still retains information, but is no longer visible to the user. (Not visible)
- OnDestroy () method
At this point, the activity is destroyed, and its life cycle is complete. (Destruction) According to the above process analysis, from the perspective of user interaction, the state of an Activity can be divided into invisible, visible available, visible unavailable, and destroyed. From the documentation provided by Android, there are three stages of the life cycle:
- Entire life cycle
The activity’s full life cycle starts with the onCreate() method and ends with the onDestroy() method. During development, we perform some initialization operations in the onCreate method, such as the initialization of the control and the setting of the control’s listening operations. For example, if we have a thread downloading data in the background, it might be created in onCreate() and destroyed in onDestroy().
- Visible Life
The visual lifecycle starts with the onStart() method and ends with the onStop() method, during which the user can see the activity on the screen. For example, when a new activity is started, the activity is no longer displayed. During this lifecycle, you can control the resources you need to present to your users. For example, you can register broadcast receivers in the onStart() method and unregister the broadcast in the onStop() method.
- Foreground Life
The foreground life cycle, during which the user can see the interaction. This lifecycle starts with onResume() and ends with onPause(). During this lifecycle, the activity precedes all activities. OnPause () is called when the device goes to sleep or when a dialog box appears. Because life cycles switch frequently between these times, the logical processing code that is processed during this life cycle should be lightweight to avoid long waits for the user by switching back and forth.
In real development, we implement our logical processing based on the activity lifecycle. The onCreate() method usually does some variable initialization during development, including variable initialization, control initialization, control setup listening, and so on. The onResume method is called when an activity regains focus because it has lost focus. In the onResume() method we can handle things like interface updates.
Here is an example to verify:
public class MainActivity extends Activity {
private static final String TAG = "ActivityLife";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG,"onCreate");
}
@Override
protected void onStart(a) {
super.onStart();
Log.d(TAG, "onStart");
}
@Override
protected void onStop(a) {
super.onStop();
Log.d(TAG, "onStop");
}
@Override
protected void onResume(a) {
super.onResume();
Log.d(TAG, "onResume");
}
@Override
protected void onPause(a) {
super.onPause();
Log.d(TAG, "onPause");
}
@Override
protected void onDestroy(a) {
super.onDestroy();
Log.d(TAG, "onDestroy"); }}Copy the code
(1) Start the activity and view the log file:
09 -01 14:32:05.850: onCreate 09 -01 14:32:05.850: onStart 09 -01 14:32:05.850: onResumeCopy the code
Through the above method analysis, we start the activity, and the activity gets the focus displayed in front of us.
(2) Start the activity with a button, but no finish() :
09 -01 15:03:59.590: onCreate 09 -01 15:03:59.590: onStart 09 -01 15:03:59.590: onResume 09 -01 15:04:23.546: onPause 09 -01 15:04:23.550: SecondActivity: onCreate 09 -01 15:04:23.550: SecondActivity: onStart 09 -01 15:04:23.550: SecondActivity: onResume 09 -01 15:04:24.130: onStopCopy the code
Through analysis, we found that our mainActivity executes onStop() method after getting focus in the SecondActivity interface. After the interface loses focus, after OnPause(). When we execute the Finish method, the onDesdroy method is executed after the onStop method is executed.
(3) Press the Home button to execute the sequence
09 -01 15:15:04.262: onPause 09 -01 15:15:04.942: onStopCopy the code
(4) Switching between horizontal and vertical screens is equivalent to recreating the activity. So statement cycle will go normal created process, generally in the actual development, we set the android: screenOrientation attribute to set whether to allow the relation panel switch.
2. The use of Activity
1, first declare in the manifest configuration file: add the activity node configuration under the Application node.
<manifest . >
<application . >
<activity android:name=".ExampleActivity" />. </application ... >... </manifest >Copy the code
There are many properties under the activity child node to configure the activity, and the only one that must be set is android:name, which determines which class our activity is in. So don’t change the name once the application is released, or it will cause application bugs. See this blog post for more property configuration. You can declare how the component works by using an intent-filter. We know that when we create an application, the system automatically creates a main activity configuration for us. As follows:
<activity android:name=".ExampleActivity" android:icon="@drawable/app_icon">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Copy the code
In this configuration, we find the node configuration main, indicating that this is the entry point for our application. The value of the LAUNCHER property identifies this as the application’s launch screen. If you want your application to be used only by itself and not by other applications, you don’t need to set up more activities. Just set up an activity with the main action and the Launcher category. Then, if you want your activity to respond to intents sent by different applications, you must define an additional intent-filter for your activity. For example, for all entries in your response, you must include one and set its and elements or element nodes, which recognize the type of the intent and respond to it.
3. Start the Activity
In Android, we use intents to transfer data or jump to activities. There are two boot options on Android.
3.1 Displaying Startup
Display launches are classes that specify the activity to start when an Intent is created. So the premise is that we already know the name of the Activity class, which is used in our development app for Activity jump.
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
Copy the code
3.2 Implicit Startup
Android provides us with many services, such as making phone calls and sending text messages. However, in our application we do not know the name of the activity class, so we need to use the implicit activity launch method.
/ / make a phone call
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:555-2368"));
startActivity(intent);
/ / text
Intent intent=new Intent();
intent.setAction("android.intent.action.SEND");
intent.setData(Uri.parse("mms:110"));
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivity(intent);
// Open the page
Intent intent=new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.baidu.com"));
startActivity(intent);
Copy the code
4. The startup mode of the Activity
There are four startup modes for activities in The Android system: Standard, singleTop, singleTask, and singleInstance. Before we look at the startup mode of an activity, let’s look at the concept of a task stack in Android. If we have a basic data structure, when we say ‘stack’, we know its characteristics: first in, last out. With that in mind, let’s talk about how many activities are arranged in Android — they are ‘loaded’ by the task stack. The diagram below:
From this diagram, we can see that the Android system manages activities on the stack in the order in which they are placed. We exit the activity from the stack when we click the back key or finish. In real development, we often have a situation where we go from activity1 — > Activity2 — >activity1, and then we go to activity2 — > Activity1. Will the system recreate an instance of Activity1 or reuse an already created instance? This involves the startup mode of our activity. Here’s a closer look at the four boot modes:
- Standard (default mode)
The default startup mode of an activity when it is created. In this startup mode, each time an activity is started, an instance is created and placed on the task stack. So if we do not execute the Finish method on the activity, there will be multiple instances of the activity.
- SingleTop (Single stack top mode)
If an activity instance already exists at the top of the current task stack, the system sends the intent to that instance through the onNewIntent method, rather than creating a new one.
- SingleTask (singleTask mode)
If an activity already exists in the task stack, we can start the activity again without having to recreate the instance. The system pushes the activity instance above the activity instance off the stack, pushing it to the top of the stack.
- SingleInstance (singleton pattern)
If application 1 has a MainActivity instance in its task stack, and application 2 also wants to activate MainActivity, it does not need to be created and the two applications share the Activity instance. Having said the basic concept, let’s verify this with a simple example: I use two activities and make them jump to each other. Let’s take a look at the code. MainActivity code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_go = (Button)findViewById(R.id.btn_go);
btn_go.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class); startActivity(intent); }}); }Copy the code
SecondActivity code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondlayout);
Button btn_goMain = (Button)findViewById(R.id.btn_goMain);
btn_goMain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SecondActivity.this,MainActivity.class); startActivity(intent); }}); }Copy the code
(1) Set the startup mode of the two activities to Standard mode. LaunchMode (Android :launchMode)
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:launchMode="standard">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity"
android:launchMode="standard"/>
</application>
Copy the code
Let’s start by building several instances of the activity and putting them on the task stack. Operation order: MainActivity->SecondActivity->MainActivity. Let’s take a screenshot to see how many times we hit the Back key to exit the app:
Looking at the screenshot, we can see that we clicked multiple times before exiting the app, indicating that we created multiple instances of the activity during the jump.
(2) singleTop mode
In this mode, if we have A->B->C->D and D is at the top of the stack, we will enter D again. If we use Standard mode, we will have A->B->C->D->D. In singleTop mode, no new instances will be created. A->B->C->D Set SecondActivity to singleTop mode
(3) singleTask mode: Run the screenshot directly, we set MainActivity as singleTask, and click Exit to directly exit the application.