Entrance to Android world - deeply unlock the secret of activity


In the oasis of Android development, the four components are like jewels on the crown, and Activity is the most eye-catching one. As a visual entrance to the user experience, every time we open an application and switch interfaces, we can't do without the presence of Activity. But that said, Activity is not a simple concept. It contains many excellent designs of Android system, which is worth exploring carefully. Today, let me show you the past and present life of Activity!


I Basic Introduction to Activity

1、 The root of activity: three treasures

To understand what activity is, you need to first understand the three cornerstones it builds: Context Window and View levels.

These components constitute the basic framework of Android applications. Their relationships and functions are as follows:

(1)、 Context : Context is an interface that provides global information about the application environment. It allows applications to access resources and lifecycle states, and is the foundation of almost all other components.

(2)、 Window : Window is an abstract class that represents a part of a user interface. It is responsible for managing the layout and drawing of views and is the top-level container of the View level.

(3)、 View Level : View is the base class of Android UI components, representing an element on the screen. ViewGroup is a subclass of View, which can contain other View objects, thus building the entire UI hierarchy.


The following Java code example demonstrates how to use these cornerstones to create a basic Android application interface:

 import android.app.Activity; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Use Context (this) to set full screen and no title bar requestWindowFeature(Window. FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  WindowManager.LayoutParams.FLAG_FULLSCREEN); //Create a layout using Context (this) LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout. VERTICAL); layout.setGravity(Gravity. CENTER);//Use Context to set the layout alignment //Create Button with Context (this) Button button = new Button(this); button.setText(R.string.button_text); //  Use Context to reference resource files button.setOnClickListener(new View. OnClickListener() { @Override public void onClick(View v) { //Use Context (this) to display Toast messages Toast.makeText(MainActivity.this,  R.string.toast_text, Toast.LENGTH_SHORT).show(); } }); //Create TextView with Context (this) TextView textView = new TextView(this); textView.setText(R.string.text_view_text); //  Use Context to reference resource files //Add Button and TextView to the layout layout.addView(button); layout.addView(textView); //Set layout as content view of activity setContentView(layout); } }

Context It is usually passed implicitly in Android applications, especially in Activity Class. stay Activity Of onCreate() In the method, this The keyword itself is a Context Object that represents the current Activity example.


The above is a standard activity creation process. As you can see, we have specified the root view for the window through setContentView, which will eventually run through the entire UI hierarchy.


2、 Activity Role of


In Android application development, Activity It is a very important component, which is part of the user interface and is used to display the screen with which the user can interact. each Activity All represent a separate screen, which can contain various views( View )And view groups( ViewGroup )For building the user interface.


Activity Its main functions include:

(1) Display user interface Activity It can include various View Objects, such as buttons, text boxes, pictures, etc., constitute the user interface.

(2) . Handling user interaction : User in Activity Operations (such as clicking a button, entering text, etc.) executed on the can be processed through the event listener.

(3) , Manage Lifecycle Activity It has its own life cycle. It will perform different operations in different states (such as running, pausing, stopping, and destroying).

(4) , start-up and destruction Activity It can be created (started) and destroyed to respond to user's operation or system requirements.


Here is a simple Activity Example, demonstrating Activity Main functions of

 import android.os.Bundle; import android.app.Activity; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MyActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Set the layout file of the activity setContentView(R.layout.activity_my); //Get Button object defined in layout file Button myButton = findViewById(R.id.my_button); //Set click event listener for Button myButton.setOnClickListener(new View. OnClickListener() { @Override public void onClick(View v) { //When the button is clicked, a Toast message is displayed Toast.makeText(MyActivity.this, "Button Clicked!",  Toast.LENGTH_SHORT).show(); } }); } }

In this example:

  • MyActivity Inherited from Activity Class, which is a Activity Class.

  • onCreate() The method is Activity A callback method in the life cycle, when Activity It will be called when it is created.

  • setContentView() Method is used to set Activity The layout file that defines Activity The user interface of.

  • findViewById() Method is used to get the View Object, a Button Object.

  • setOnClickListener() The method is Button A click event listener is set. When a button is clicked, it will call onClick() Method, and display a Toast Message.


In addition, in order to make the above code work properly, you need to res/layout/activity_my.xml Define the corresponding layout in the file:

 <LinearLayout xmlns:android=" http://schemas.android.com/apk/res/android " android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center"> <Button android:id="@+id/my_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" /> </LinearLayout>

2、 Life cycle: control the world of activity

Android Activity The lifecycle of consists of a series of callback methods (also called lifecycle methods) Activity The Android system automatically calls when switching between different states of. Understanding these lifecycle approaches for proper management Activity The state and resources of are critical.


 Insert picture description here


The following are Activity The main methods of the life cycle and the order in which they are called:

  1. onCreate(Bundle savedInstanceState) -When Activity 'is called the first time it is created.
  2. onStart() - Activity Called when it becomes visible.
  3. onResume() - Activity Called when ready to interact with the user.
  4. onPause() - Activity Called when part of the focus is lost but still visible, usually used to save the state.
  5. onStop() - Activity Called when it is no longer visible.
  6. onRestart() - Activity Called when returning from the stopped state to the started state.
  7. onDestroy() - Activity Called before being destroyed.

The following is a simple Java code example that demonstrates how to rewrite these life cycle methods and print the corresponding status on the console:

 import android.app.Activity; import android.os.Bundle; import android.util.Log; public class LifecycleActivity extends Activity { private static final String TAG = "LifecycleActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate"); //Set layout and other initialization operations } @Override protected void onStart() { super.onStart(); Log.d(TAG, "onStart"); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume"); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause"); } @Override protected void onStop() { super.onStop(); Log.d(TAG, "onStop"); } @Override protected void onRestart() { super.onRestart(); Log.d(TAG, "onRestart"); } @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy"); } }

In Android development, the console log output is viewed through Logcat. When Activity When the lifecycle method of is called, you can see the corresponding log output in the Logcat window of Android Studio.


The following are LifecycleActivity The log output information and order in. Suppose the user opens this Activity , then switch it to the background immediately (for example, by pressing the Home key), then switch back, and finally close Activity

 D/LifecycleActivity(23333): onCreate D/LifecycleActivity(23333): onStart D/LifecycleActivity(23333): onResume

When Activity When switched to the background (partially out of focus but still visible):

 D/LifecycleActivity(23333): onPause

When Activity When it becomes visible again:

 D/LifecycleActivity(23333): onResume

When Activity When switched to the background and completely stopped:

 D/LifecycleActivity(23333): onStop

If Activity Restart by the system (for example, when the device resource is insufficient):

 D/LifecycleActivity(23333): onRestart D/LifecycleActivity(23333): onStart D/LifecycleActivity(23333): onResume

When the user closes Activity perhaps Activity When destroyed:

 D/LifecycleActivity(23333): onPause D/LifecycleActivity(23333): onStop D/LifecycleActivity(23333): onDestroy

Note that the exact order of log output may vary depending on user behavior and system state. For example, if the user Activity The device is restarted during runtime, or the system is terminated for resource recovery Activity , you may not see onPause() and onStop() Method. In addition, if Activity In the background, the user pressed the Back key, Activity Will be destroyed, you will see onPause() onStop() and onDestroy() Instead of seeing onRestart()


It is important to understand the life cycle, because we need to perform corresponding operations at the appropriate nodes, such as data loading, UI update, etc., to ensure the smoothness and normal operation of the application.


3、 Task and Return Stack: Controlling the Complicated World of Programs

 Insert picture description here


1. Concept of Task

The task is to maintain a series of Activity Containers, these Activity Arranged according to the order with which users interact. The concept of task is very important for user navigation and application multitasking.

  • Starting point of the task : It is usually started from the main screen of the device. When the user clicks the application icon or shortcut on the main screen, the application task will be started or brought to the foreground.

  • Task creation : If the application has not been used before (that is, there is no existing task), the system will be the "master" of the application Activity Create a new task, this Activity Will be the first in the task Activity , which is also the root of the return stack.


2. Back Stack

The return stack is a data structure inside the task, which is used to store Activity So that the user can press the "Return" button Activity Navigation between.

  • LIFO : The return stack follows the last in, first out principle, that is, the last enabled Activity Will be at the top of the stack and will be destroyed first.

  • Start and stop of activity : When a new Activity When it is started, it will be pushed back to the top of the stack and become the current focus Activity previous Activity It will enter the stop state, but its state will be saved so that the user can recover when returning.

  • User navigation : The user can press the "Return" button to Activity The system will automatically destroy the top of the stack Activity , and restore the previous Activity


3. Relationship between task and return stack

 Insert picture description here

  • Maintenance of tasks : The Android system will maintain the return stack of each task. Even if the task is placed in the background, its return stack will remain unchanged.

  • The foreground and background of the task : The task can enter the foreground or background. When the user starts a new task or goes to the main screen by pressing the "Home" button, the current task will enter the background, but its return stack will remain unchanged.

  • Recovery of tasks : When the task is selected again by the user, it can return to the foreground from the background, and the user can continue to operate from the state they left.


4. Multitasking

  • Multi task scenario : Users can switch between multiple tasks, or even start activities in other applications on the device. For example, users may view mail in one task and browse web pages in another task.

  • Task switching : Users can switch between different tasks through the main screen or "Recently Applied" (recent screen preview).


By understanding the principles of tasks and return stacks, we can better design the navigation structure of applications and provide a smooth and intuitive user experience. At the same time, different startup modes and Intent flags can be reasonably used to control the behavior of tasks in a fine-grained way.


4、 Four standard startup modes: magic of summoning activity

In Android development, Activity The startup mode of determines the relationship between multiple instances and tasks. Android provides four standard startup modes:


1、 Standard


Every start Activity A new instance will be created regardless of whether it already exists.

Standard mode is the default startup mode of Android. If you do not make any settings in the configuration file, this activity is in Standard mode. In this mode, An activity can have multiple instances. Each time an activity is started, the system will create a new activity instance regardless of whether there is already an instance of the activity in the task stack.

 <activity android:name=".StandardActivity"> <!--  Other configurations --> </activity>
  • Best Practices : By default, most Activity Standard mode should be used.
  • Applicable scenarios : When you want to create a new Activity Instance, or when Activity When there is no specific task or lifecycle association between them.

2、 SingleTop (stack top reuse mode)


If Activity If it is already at the top of the task stack, it will not create a new instance, but reuse the current instance. If it is not at the top of the stack, a new instance will be created.

 <activity android:name=".SingleTopActivity" android:launchMode="singleTop"> <!--  Other configurations --> </activity>
  • Best Practices : using this mode Activity It should be able to handle unexpected repeated start requests.

  • Applicable scenarios : When you want Activity Can receive from others Activity And if it is already at the top of the stack, the instance should not be re created. For example, news details in a news reader application Activity , when the user starts the same detail from different news items Activity Multiple instances should not be created.


3、 SingleTask (single task mode)


The activity in SingleTask mode has only one instance in the same Task. If the activity is already at the top of the stack, the system will not create a new activity instance, as in SingleTop mode. However, when an activity already exists but is not at the top of the stack, the system will move the activity to the top of the stack and take the activity above it out of the stack.

 <activity android:name=".SingleTaskActivity" android:launchMode="singleTask"> <!--  Other configurations --> </activity>
  • Best Practices : using this mode Activity It should be a single entry point in the application and can be handled correctly Intent Task fallback behavior for.

  • Applicable scenarios : When you want to have only one task Activity Instance. If multiple instances need to be started, the system will pass the intention to the existing instance. For example, an application's main Activity , it may need to receive Activity Or a shopping cart in a shopping application Activity , users may add items to the shopping cart from anywhere in the application.


4、 SingleInstance (single instance mode)


Only one in the whole system Activity Instance, and it is alone in a new task stack.

SingleInstance mode is different from SingleTask mode, SingleTask is just a single instance in the task stack. There can be multiple SingleTask activity instances in the system, while SingleInstance activity has only one instance in the whole system. When a SingleInstance activity is started, the system will create a new task stack, and this task stack has only this activity.

 <activity android:name=".SingleInstanceActivity" android:launchMode="singleInstance"> <!--  Other configurations --> </activity>

SingleInstance mode is not commonly used. If we set an activity to SingleInstance mode, it will start slowly, and the switching effect is not good, affecting the user experience.

It is often used between multiple applications. For example, an activity in a TV Launcher can be started in any situation through a key on the remote control. This activity can be set to SingleInstance mode. When you press the key in an application to start the activity, and press the Return key after processing, you will return to the previous application to start it, without affecting the user experience.

  • Good practice : using this mode Activity It should be completely independent and not be associated with other Activity Share tasks.
  • Applicable scenarios : When you need a Activity , and the Activity It should always be at the beginning of a new task. For example, for an application that requires users to log in, log in Activity Can be set to singleInstance Mode to avoid the login status being changed Activity Interference.

The following are different startup modes using Java code Activity Example of:

 import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnStandard = findViewById(R.id.btn_standard); Button btnSingleTop = findViewById(R.id.btn_single_top); Button btnSingleTask = findViewById(R.id.btn_single_task); Button btnSingleInstance = findViewById(R.id.btn_single_instance); //Start the activity in standard mode btnStandard.setOnClickListener(new View. OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,  StandardActivity.class); startActivity(intent); } }); //Start activity in singleTop mode btnSingleTop.setOnClickListener(new View. OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,  SingleTopActivity.class); startActivity(intent); } }); //Start activity in singleTask mode btnSingleTask.setOnClickListener(new View. OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,  SingleTaskActivity.class); startActivity(intent); } }); //Start activity in singleInstance mode btnSingleInstance.setOnClickListener(new View. OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,  SingleInstanceActivity.class); startActivity(intent); } }); } }

V Additional changes to the flags option Activity Start behavior

1、 Introduction to flags and their functions


In Android, you can use the Intent Set flags on the object to change Activity Behavior at startup. These flags provide Activity How to initiate additional control over its relationship with the task. The following are some common flags options and their functions:

  • FLAG_ACTIVITY_NEW_TASK : Make Activity Become the beginning of a new task.

  • FLAG_ACTIVITY_CLEAR_TOP : If the same exists Intent Of Activity Instance, all the above Activity Out of stack.

  • FLAG_ACTIVITY_SINGLE_TOP : Ensure Activity Duplicate instances are not created at the top of the task stack.

  • FLAG_ACTIVITY_CLEAR_TASK : Clear the entire task stack, except the Activity

  • FLAG_ACTIVITY_TASK_ON_HOME : When the user returns to the main screen, if this is at the top of the task stack Activity , it will not be restarted.


The following is an example of Java code that uses these flags:

 import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnNewTask = findViewById(R.id.btn_new_task); Button btnClearTop = findViewById(R.id.btn_clear_top); Button btnSingleTop = findViewById(R.id.btn_single_top); Button btnClearTask = findViewById(R.id.btn_clear_task); //Start a new task using FLAG_ACTIVITY_NEW_TASK btnNewTask.setOnClickListener(new View. OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,  NewTaskActivity.class); intent.addFlags(Intent. FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }); //Use FLAG_ACTIVITY_CLEAR_TOP to ensure that only one instance is on the top of the stack btnClearTop.setOnClickListener(new View. OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,  ClearTopActivity.class); intent.addFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }); //Use FLAG_ACTIVITY_SINGLE_TOP to ensure that no duplicate instances are on the top of the stack btnSingleTop.setOnClickListener(new View. OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,  SingleTopActivity.class); intent.addFlags(Intent. FLAG_ACTIVITY_SINGLE_TOP); startActivity(intent); } }); //Use FLAG_ACTIVITY_CLEAR_TASK to clear the task stack btnClearTask.setOnClickListener(new View. OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,  ClearTaskActivity.class); intent.addFlags(Intent. FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } }); } }

In this example, we create a main Activity MainActivity ), which contains four buttons, each of which is used to launch Activity When the user clicks these buttons, a Intent Add the corresponding flags, and then use startActivity(intent) start-up Activity

Please note that in order for the above code to work properly, you need to AndroidManifest.xml These are declared in the file Activity And set appropriate startup modes for them (if any). At the same time, you also need to provide these buttons in the layout file activity_main.xml The corresponding ID is defined in.

Use flags to Activity It is a common practice in Android application development to modify the startup behavior of the.


2. Best practices for additional control over activities using flags options


use Intent The flags option of is Activity Providing additional control is a powerful mechanism that can change Activity And task management mode. Here are some best practices on how to use these flags:


(1) . Use FLAG_ACTIVITY_CLEAR_TOP for status management

When you want users to Activity When returning, you can return to the specific state of the application. You can use FLAG_ACTIVITY_CLEAR_TOP This will remove the target Activity All above Activity To ensure that the user will not fall back to an intermediate state.

(2) Use FLAG_ACTIVITY_NEW_TASK to start a new task

If you want to start Activity It should be run independently of the current task FLAG_ACTIVITY_NEW_TASK This creates a dialog box or mode Activity It is very useful when.

(3) Avoid abusing FLAG_ACTIVITY_CLEAR_TASK

FLAG_ACTIVITY_CLEAR_TASK The target in the task stack will be cleared Activity All except Activity This may cause users to lose their location, so use it only when they really need it.

(4) , using FLAG_ACTIVITY_REORDER_TO_FRONT

If you use FLAG_ACTIVITY_SINGLE_TOP And if you want to move the existing task instance to the foreground, you can use FLAG_ACTIVITY_REORDER_TO_FRONT This is useful in some scenarios where existing instances need to be reordered.

(5) Consider user experience

When using flags, always consider the user experience. For example, using FLAG_ACTIVITY_CLEAR_TOP Users may lose their position in the application, so use it carefully.

(6) . Use multiple flags together

Sometimes you may need to use multiple flags together to implement specific behaviors. For example, FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP Can ensure that even if Activity It already exists, no new instance will be created, and all the above instances will be cleared Activity

(7) Avoid excessive use of flags

Excessive use of flags may make the navigation logic of the application complex and difficult to maintain. Use them only when you really need them.

(8) Test different equipment and configurations

Different devices and Android versions may interpret flags slightly differently. Make sure to test your app on multiple devices and Android configurations.


Conclusion:

Whether it is the activity maintenance technology or the Intent mechanism for programmatically starting activity, it is an indispensable big bear mechanism in Android development. These contents are worthy of further exploration, so as to master more cutting-edge postures of using activity.


In short, Although Activity is the entrance to Android, it also contains the most profound thinking in system design. We have much to learn and explore. We look forward to further exploration in the next chapter - keeping alive Intent and its extensions, as well as URI Scheme and multi-path implementation.

  • thirty-one
    give the thumbs-up
  • step on
  • fifteen
    Collection
    Think it's good? One click collection
  •  Reward
    Reward
  • zero
    comment

Is "relevant recommendation" helpful to you?

  • Very unhelpful
  • No help
  • commonly
  • to be helpful to
  • Very helpful
Submit
comment
Add Red Packet

Please fill in the red envelope greeting or title

individual

The minimum number of red packets is 10

element

The minimum amount of red packet is 5 yuan

Current balance three point four three element Go to recharge>
To be paid: ten element
Achieve 100 million technicians!
After receiving, you will automatically become a fan of the blogger and the red envelope owner rule
hope_wisdom
Red packet sent

Reward the author

W rain or shine w

Your encouragement will be the greatest impetus for my creation

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
Scan code for payment: ¥1
Obtaining
Scan code for payment

Your balance is insufficient, please change the scanning code to pay or Recharge

Reward the author

Paid in element
Payment with balance
Click to retrieve
Scan code for payment
Wallet balance zero

Deduction description:

1. The balance is the virtual currency of wallet recharge, and the payment amount is deducted at a ratio of 1:1.
2. The balance cannot be directly purchased and downloaded, but VIP, paid columns and courses can be purchased.

Balance recharge