Exploring the Way of Activity Components: Uncovering the Charm of Android Program Activities

Chapter 4: Program Activity Unit Activity

  • Activity is an important component in Android app. It provides a window for the user to interact with. Usually the window fills the screen, but sometimes it is smaller than the screen and floats over other windows

four major components

Application components are the basic building blocks of Android applications. There are four different application component types

  • Activity: Activity is the entry point for interacting with the user. It represents a single screen with an interface.
  • Service: A service is a component that runs in the background to perform long-running operations or execute jobs for remote processes. The Service does not provide a user interface.
  • ContentProvider (content provider): The content provider manages a set of shared application data and is the data interface between the underlying data storage and the upper application.
  • BroadcastReceiver: A broadcast receiver is a component that responds to system-wide broadcast notifications. Many broadcasts are system-initiated—for example, broadcasts announcing that the screen has turned off, the battery is low, or a picture has been taken.
  • Start components: Three of the four component types—Activities, Services, and Broadcast Receivers—are started by asynchronous messages called Intents. Intents glue components together at runtime (think of Intents as messengers that request actions from other components).

Activity life cycle

Activity's god cycle refers to the entire state of Activity from creation to destruction. The process can be roughly divided into five states, starting state, running state, paused state, stopped state, and destroyed state.

insert image description here
insert image description here

Activity's startup mode

  • Android's task stack is a container used to store Activity instances. The biggest feature of the task stack is: first in, last out, and two basic operations: push and pop. Open the Activity, perform the Activity stack operation; destroy the Activity, and perform the pop operation. Attributes that do not need to be configured <activity>, android:launchModeof course, you can also specify the attribute value asstandard
  • There are four startup modes of activity: standard, singleTop, singleTask, singleInstance.

standard

  • The standard mode is the default startup mode. The characteristics of this method are: every time an activity is started, a new instance will be created on the top of the stack.
  • Alarm clock programs usually use this mode .
    insert image description here

singleTop

  • This mode only judges whether the activity to be started is at the top of the stack. If it is at the top of the stack, it will be reused directly, otherwise a new instance will be created.
  • <activity>specify attributesandroid:launchMode="singleTop"
  • Browser bookmarks usually follow this pattern .
    insert image description here

singleInstance

  • This startup mode is special, because it will enable a new stack structure, place Acitvity in this new stack structure, and ensure that no other Activity instances will enter.
  • The desktop in Android uses this mode.

Two Activity instances are placed in different stack structures. The schematic diagram of singleInstance is as follows
insert image description here

singleTask

  • : If the Activity to be started already exists in the task stack, no new instance will be created, but all instances above the Activity will be popped from the stack, and the Activity instance will be moved to the top of the stack, and its onNewIntent() will be called Method; if the Activity to be started does not exist in the task stack, a new instance will be created and added to the task stack.
  • FirstActivitproperties of yandroid:launchMode="singleTask"
  • This mode is commonly used in the incoming call interface
    insert image description here

Intent

insert image description here

  • Intent (intent) is an important way to protect between components in the program. It can not only specify the actions to be performed by the current component, but also transfer data between different components.
  • Intent is divided into explicit Intent and implicit Intent
    • Explicit Intent: You need to directly specify the target component
    //创建一个Intent对象,其中第1个参数为Context表示当前的Activity对象,第2个参数表示要启动的目标Activity。
    Intent intent = new Intent(this, SignInActivity.class);
    startActivity(intent);
    
    • Implicit Intent: No need to explicitly indicate the target component that needs to be activated
      insert image description here
  • When an implicit Intent is sent, the Android system will match it with the filter of each component in the program. The matching attributes include action, data, and category. All three attributes must be matched successfully to invoke the corresponding component.
  • action: used to specify the action of the Intent object
//在清单文件中为Activity添加<intent-filter>标签时,必须添加action属性,否则隐式Intent无法开启该Activity
<intent-filter>
    <action android:name="android.intent.action.EDIT"/>
    <action android:name="android.intent.action.VIEW"/>
</intent-filter>

  • data: The URI of the specified data or the data MIME type, its value is usually associated with the action attribute of the Intent
<intent-filter>
<data android:mimeType="video/mpeg" android:scheme="http..."/>
    <data android:mimeType="audio/mpeg" android:scheme="http..."/>
</intent-filter>
  • As long as the data carried by the implicit Intent is the same as any data statement in the IntentFilter, the data attribute will match successfully
  • category: used to add additional information to the action
<intent-filter>
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
</intent-filter>

  • An IntentFilter may declare no category attribute, or declare multiple category attributes.
  • The category declared in the implicit Intent must all match the category in a certain IntentFilter to be considered a successful match
  • Note: Only when the number of category attributes listed in the IntentFilter is greater than or equal to the number of category attributes carried by the implicit Intent can the category attributes be matched successfully. If an implicit Intent does not set the category attribute, then it can be matched by any IntentFilter (filter) category

IntentFilter

  • Use > to specify various intent filters. The function of the filter is to declare how other app components activate the activity <activity>.<intent-filter
  • When creating a new app, a root activity is automatically created, which contains an intent filter, which declares that this activity responds to the "main" action and is in the "launcher" category, 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>
    

Data transfer between activities

The putExtra() method transfers data

putExtra() is a method in the Intent class, which is used to add additional information to the Intent so that data can be passed when the Activity is started. Its basic usage is as follows:

  1. Add a string type of additional information to the Intent:

    Intent intent = new Intent(this, TargetActivity.class);
    intent.putExtra("key", "value");
    startActivity(intent);
    
  2. Add additional information of an integer type to the Intent:

    Intent intent = new Intent(this, TargetActivity.class);
    intent.putExtra("key", 123);
    startActivity(intent);
    
  3. Add a Boolean type of additional information to the Intent:

    Intent intent = new Intent(this, TargetActivity.class);
    intent.putExtra("key", true);
    startActivity(intent);
    
  4. Add additional information of a serialized object type to the Intent:

    Intent intent = new Intent(this, TargetActivity.class);
    MyObject myObject = new MyObject();
    intent.putExtra("key", myObject);
    startActivity(intent);
    
  • It should be noted that the putExtra() method supports passing multiple additional information, which can be achieved by calling the putExtra() method multiple times. In the Activity at the receiving end, the passed Intent object can be obtained through the getIntent() method, and the value of the additional information can be obtained through the getXXXExtra() method.

Bundle class passing data

Bundle is a class used to transfer data, it can transfer data between different components, such as Activity, Service, BroadcastReceiver, etc. Bundle can store multiple types of data, such as strings, integers, Booleans, serialized objects, etc., and is very convenient to use. The following is how to use the Bundle class to pass data:

  1. Create a Bundle object in the sender's component and add the data that needs to be passed to it:
    Intent intent = new Intent(this, TargetActivity.class);
    Bundle bundle = new Bundle();
    bundle.putString("key1", "value1");
    bundle.putInt("key2", 123);
    bundle.putBoolean("key3", true);
    MyObject myObject = new MyObject();
    bundle.putSerializable("key4", myObject);
    intent.putExtras(bundle);
    startActivity(intent);
    
  2. Get the Bundle object in the component on the receiving end, and get the required data from it:
    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    String value1 = bundle.getString("key1");
    int value2 = bundle.getInt("key2");
    boolean value3 = bundle.getBoolean("key3");
    MyObject myObject = (MyObject) bundle.getSerializable("key4");
    
  • It should be noted that when the Bundle class transfers data, the type of the data must match the type that the component at the receiving end can handle, otherwise it will cause a type conversion exception. At the same time, when transferring large amounts of data, you should consider using the Parcelable interface instead of the Serializable interface to improve performance.

Data return between activities

  • The startActivityForResult() method is used to start an Activity, and when the opened Activity is destroyed, it is hoped to return data from it
Intent intent = new Intent(this, TargetActivity.class);
startActivityForResult(intent, requestCode);
// 意图 请求码(用于标识请求的来源)
  • The setResult() method is used to carry data back
Intent intent = new Intent();
intent.putExtra("result", resultData);
// 返回码 意图(用于携带数据并传回上一个界面)
setResult(Activity.RESULT_OK, intent);
finish();
  • The OnActivityResult() method is used to receive the returned data and identify the source of the data according to the passed parameters requestCode and resultCode
@Override
// A、requestCode,表示在启动Activity时传递的请求码
// resultCode,表示在返回数据时传入结果码
// data,表示携带返回数据的Intent
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
    
    if (resultCode == Activity.RESULT_OK && requestCode == requestCode) {
    
    
        String resultData = data.getStringExtra("result");
        // 处理返回结果
    }
}

exercise summary

  1. Briefly describe the method of the life cycle of Activity in Android and when is it called?
    insert image description here

  1. onCreate(): Called when the Activity is created to perform some initialization operations, such as loading layout files, binding controls, and so on.
  2. onStart(): Called when the Activity becomes visible. At this time, the Activity has not yet obtained the user's focus and cannot interact with the user.
  3. onResume(): Called when the Activity gets the user focus and starts to interact with the user. At this time, the Activity is running in the foreground.
  4. onPause(): Called when the Activity loses user focus but is still visible. At this time, some temporary data can be saved or some animation effects can be paused.
  5. onStop(): Called when the Activity is completely invisible, you can release some resources or stop some services at this time.
  6. onRestart(): Called when the Activity is restarted from the stopped state, the Activity will re-execute the onStart() and onResume() methods.
  7. onDestroy(): Called when the Activity is destroyed, you can release some resources or stop some services at this time.

  1. The four startup modes of Activity in Android are:
    1. Standard (standard mode): Every time you start the Activity, a new instance will be created, regardless of whether this instance already exists, even if it is the Activity in the same application. such as alarm clock program
    2. singleTop (stack top reuse mode): If the Activity to be started is already at the top of the task stack, a new instance will not be created, but the instance will be used directly and its onNewIntent() method called; if the Activity to be started is not At the top of the stack, a new instance is created.
    3. singleTask (in-stack multiplexing mode): If the Activity to be started already exists in the task stack, no new instance will be created, but all the instances above the Activity will be popped from the stack, and the Activity instance will be moved to the stack at the same time top, and call its onNewIntent() method; if the Activity to be started does not exist in the task stack, a new instance will be created and added to the task stack.
    4. singleInstance (single instance mode): There is only one instance in an independent task stack, and even different applications cannot create new instances in the task stack. This pattern is generally used for application components that need to be globally unique, such as the dialer interface.

  1. Briefly describe the role of Activity, Intent, and IntentFilter?
    1. Activity: Activity is the interface part of the Android application, which is responsible for interacting with the user, receiving user input, displaying data, etc. Each Activity has its own life cycle and state, and can be started and passed data through Intent.
    2. Intent: Intent is a mechanism for passing messages and starting components in Android. It can transfer data between different components, start Activity, Service or BroadcastReceiver, etc. Intent can contain data and operations, which are used to describe the actions that need to be performed and the data to be manipulated.
    3. IntentFilter: IntentFilter is a mechanism for declaring which Intents a component can receive. It can specify the action, category, and data attributes of the Intent to filter the Intents that can be received. When an Intent is sent, the system will match the appropriate component to process the Intent according to the properties of the Intent and the registered IntentFilter.

  1. Activity can set its layout file
    A, setContentViews()
    B, setContentView()
    C, setLayoutView()
    D, setLayoutViews() through the () method

  1. Activity can set its layout file through the () method, and display the view on the interface.
    A. setLayoutView()
    B. setContentView()
    C. setLayoutViews()
    D. setContentViews()

  1. The execution method when the Activity gets the focus is
    A, onStart()
    B, onResume()
    C, onPause()
    D, onDestroy()

  1. ProgressBar is usually used to access the network display loading dialog and to show the progress of downloading files. It has two manifestations, one is horizontal and the other is circular ( )

  1. Activity can run without registering in the AndroidManifest.xml file ( × )
    • In Android, if you want to start an Activity, you must register the Activity in the AndroidManifest.xml file, otherwise it will cause a runtime error. The AndroidManifest.xml file is the configuration file of the Android application, which contains various information of the application, including declaration information of components such as Activity, Service, BroadcastReceiver, and ContentProvider. When the application starts, the system will read the information in the AndroidManifest.xml file and start the corresponding components according to the configuration therein.
    • If an Activity is not registered in the AndroidManifest.xml file, when we try to start the Activity, the system will throw an ActivityNotFoundException because the system cannot find the declaration information of the Activity. Therefore, every Activity that needs to be started must be registered in the AndroidManifest.xml file, otherwise the application will not work properly.

  1. Activity is not a subclass of Context ( × )
    • Activity is a subclass of Context. Activity inherits from the ContextThemeWrapper class, and the ContextThemeWrapper class inherits from the ContextWrapper class, and the ContextWrapper class inherits from the Context class. Therefore, Activity inherits all the methods and properties of the Context class, and also adds some methods and properties of its own. Therefore, we can directly use the methods and properties of Context in the Activity.

  1. In the target Activity, usually use the setResult method to set the return data ( )

  1. Usually an application corresponds to a task stack. By default, every time an Activity is started, it will be pushed onto the stack and placed at the top of the stack ( )

  1. Activity's startActivityForResult() method receives two parameters, the first parameter is Intent, and the second parameter is ( request code ), which is used to determine the source of data

  1. ( ProgressBar ) is usually used to access the network display loading dialog box and the progress displayed when downloading files

  1. Activity's life cycle is divided into three states, namely running state, ( paused state ) and stopped state

  1. Activity will execute onCreate(), ( onStart() ), onResume() three methods from startup to fully appearing in front of the user

  1. In the method of the Activity life cycle, the ( onCreate() ) method is used to initialize the instance object after the Activity instance object is created

  1. When creating ( Activity ), you need to inherit the parent class android.app.Activity or its subclasses

Guess you like

Origin blog.csdn.net/yang2330648064/article/details/131177462