I Basic Introduction to Activity
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); } }
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(); } }); } }
-
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.
<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
-
onCreate(Bundle savedInstanceState) -When Activity 'is called the first time it is created. onStart() - Activity Called when it becomes visible. onResume() - Activity Called when ready to interact with the user. onPause() - Activity Called when part of the focus is lost but still visible, usually used to save the state. onStop() - Activity Called when it is no longer visible. onRestart() - Activity Called when returning from the stopped state to the started state. onDestroy() - Activity Called before being destroyed.
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"); } }
D/LifecycleActivity(23333): onCreate D/LifecycleActivity(23333): onStart D/LifecycleActivity(23333): onResume
D/LifecycleActivity(23333): onPause
D/LifecycleActivity(23333): onResume
D/LifecycleActivity(23333): onStop
D/LifecycleActivity(23333): onRestart D/LifecycleActivity(23333): onStart D/LifecycleActivity(23333): onResume
D/LifecycleActivity(23333): onPause D/LifecycleActivity(23333): onStop D/LifecycleActivity(23333): onDestroy
3、 Task and Return Stack: Controlling the Complicated World of Programs
1. Concept of Task
-
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
-
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
-
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).
4、 Four standard startup modes: magic of summoning activity
<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.
<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.
<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.
<activity android:name=".SingleInstanceActivity" android:launchMode="singleInstance"> <!-- Other configurations --> </activity>
-
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.
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
-
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.
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); } }); } }
Conclusion: