Activity life cycle and startup mode

1. Activity life cycle


The life cycle of Activity is divided into two situations:

  1. Typical situation : Changes in the life cycle of an Activity with user participation.
  2. Exception : The Activity is recycled by the system or the Activity is destroyed and rebuilt because the configuration of the current device is changed.

1. Life cycle analysis in typical cases

  1. Under normal circumstances, it will go through the following life cycle:

    method Function describe
    onCreate Activity is being created Can do some initialization work, setContentView, etc.
    onRestart Activity is restarting Activity changes from invisible to visible
    onStart Activity is being started, about to start Activity is already visible, but not in the foreground yet
    onResume Activity has started activity Activity is already visible and has appeared in the foreground
    onPause Activity is stopping You can do the work of storing data, stopping animation, etc., but pay attention to the time-consuming
    onStop Activity is about to stop You can do some heavyweight recycling work, but also pay attention to the time-consuming
    onDestroy Activity is being destroyed Can do final recycling and resource release
  2. The switching flow chart of the life cycle:

    write picture description here

  3. some specific instructions

    1. Start Activity for the first time: onCreate-> onStart-> onResume.
    2. The user opens a new Activity or switches to the desktop: onPause->onStop
      • If the new Act adopts the transparent theme, the current Act will not be calledonStrop
    3. When the user returns to the original Act again: onRestart-> onStart->onResume
    4. When the user presses the back key to go back: onPause-> onStop->onDestroy
    5. When the Act is re-opened after being recycled by the system, the lifecycle callback process is the same as 1, but a method for restoring data will be called back onRestoreInstanceState.
    6. Pairing of callback methods:

      Cycle method 1 Cycle method 2 Activity state action illustrate
      onCreate onDestroy create-destroy Only one call is possible
      onStart onStop visible - invisible User actions and device screen on and off, may be called multiple times
      onResume onPause front desk, back desk User actions and device screen on and off, may be called multiple times
  4. The process of starting Act2 from Act1:

    Act1.onPause-> Act2.onCreate-> Act2.onStart-> Act2.onResume-> Act1.onStop
    Obviously, the onPause of the old Act is called first, so onPausedon't do time-consuming operations inside.

2. Life cycle analysis under abnormal conditions

  1. The resource-related system configuration changed, causing the Activity to be killed and recreated:

    image

    • In the system onSaveInstanceStateand onRestoreInstanceStatemethod, the system automatically does some recovery work: saves the current attempt structure of the Act, and restores these data after the Act restarts.
      • We can override these two methods to save and restore custom data
      • In this exceptional case, onCreatethe parameter is the bundle to be saved
      • Under normal circumstances, onCreatethe parameter of , is null, and onRestoreInstanceStatewill not be called back.
  2. Insufficient resource memory, causing low-priority activities to be killed

    • When the memory is insufficient, the system will kill the process where the target Activity is located according to the priority, and then store and restore the data through onSaveInstanceStateand onRestoreInstanceStatemethods.
      • If a process does not have the four components executing, then the process will be killed by the system very quickly.
      • So put the background work into the Service to ensure that the process has a certain priority and will not be easily killed.
    • Priority Description:
      • Foreground Activity: The Activity that is interacting with the user has the highest priority
      • Visible but non-foreground Activity: For example, a dialog box pops up, causing the Activity to be visible but unable to interact in the background, and the priority is second.
      • Background Activity: The activity that has been suspended has the lowest priority.

2. Activity startup mode


  1. LaunchMode:standard、singleTop、singleTask和singleInstance。
  2. Activity's Flags:
    • Intent.FLAG_ACTIVITY_NEW_TASK
    • Intent.FLAG_ACTIVITY_SINGLE_TOP
    • Intent.FLAG_ACTIVITY_CLEAR_TOP
    • Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS

1. LaunchMode

  1. standard: Standard mode, the system default mode.

    • If you use ApplicationContext to start Activity, an error will be reported, because non-Activity Context has no task stack.
    • The solution is to specify the Intent.FLAG_ACTIVITY_NEW_TASKflag, which is actually started in singleTask mode.
  2. singleTop: stack top multiplexing mode.

    • When the activated Act is already at the top of the stack, an Act will not be recreated and onNewIntentwill be called back.
    • When the Act is not at the top of the stack, the Act will still be recreated.
  3. singleTask: In-stack multiplexing mode. This is a single instance pattern.

    • As long as the Act is in a task stack, launching the Act multiple times will not recreate the instance.
    • Process: If Act A is started with SingleTask, the system will first look for the existence of the task stack that A wants:
      1. If it doesn't exist, create a task stack, then create an instance of A, and push A onto the stack.
      2. If it exists, then judge whether there is A in the stack.
        1. If it does not exist, an instance of A is created and pushed onto the stack.
        2. If it already exists, move A to the top of the stack and call back the onNewIntentmethod.
    • A few examples:
      • S1:ABC already exists, start D(S2) with SingleTask.
        • Create S2 first, then create an instance of A, and push it into S2.
      • S1:ABC already exists, start D(S1) with SingleTask.
        • Create an instance of A and push into S2.
      • S1: ADBC ​​already exists, start D(S1) with SingleTask.
        • Switching D of S1 directly to the top of the stack will trigger a callback onNewIntent.
        • BC is popped due to the nature of the stack
  4. singleInstance: Single instance mode. This is an enhanced singleTask mode.

    • Acts in this mode must be placed individually in a task stack.
    • When Act is started for the first time, the system will create a new task stack for it, and then A exists alone in this task stack.
    • The next time an Act is started, it follows the multiplexing feature in the stack, and subsequent start requests will not create a new Act.
  5. TaskAffinity and allowTaskReparenting

    1. Example 1

      • App1 and App2 exist:

        App Activity taskAffinity allowTaskReparenting
        App1 Act1 (entrance) com.test.affinity true
        App2 Act2 (entrance) com.test.affinity false
      • Operation process: start App1.Act1, press Home, and start App2 on the desktop
      • Result: App1.Act1 is still displayed, not App2.Act2
    2. Example 2

      • App1 and App2 exist

        App Activity taskAffinity
        App1 Act1 com.test.affinity
        App1 Act2 (entrance) default
        App2 Act3 (entrance) com.test.affinity

        Act2 sets the button, press it to start Act1 ( intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)).

      • Operation process: start App2, press home, then start App1, then press the back key and click the button to start Act1.

      • Result: Desktop display order: Act3, Desktop, Act2, Act1, Act3.
  6. How to set startup mode:

    1. specified in the manifst. Unable to set FLAG_ACTIVITY_CLEART_TOPlogo.
    2. Set the Flag flag for the intent. The SingleInstance mode cannot be specified.
      • When these two methods exist at the same time, the second one shall prevail

2. The Flags of Activity, the commonly used ones are as follows:

  • Intent.FLAG_ACTIVITY_NEW_TASK
    • Description: Specify the singleTask startup mode for the Activity
  • Intent.FLAG_ACTIVITY_SINGLE_TOP
    • Description: Specify singleTop startup mode for Activity
  • Intent.FLAG_ACTIVITY_CLEAR_TOP
    • Description: When an Activity with this flag is started, all activities above it in the same task stack must pop out of the stack.
      • If the Activity is started in singleTask mode, and an instance of the Activity already exists, the system will call its onNewIntent.
      • If this Activity is started in standard mode, then in addition to the Activity located above it, it will pop out of the stack, and the system will recreate an instance and put it on the stack.
  • Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
    • Description: Activities with this flag will not appear in the list of historical activities. It is equivalent to android:excludeFromRecents="true". This flag is useful in some cases when we don't want the user to go back to our Activity through the history list.

3. Matching rules of IntentFilter

  • Only if action, category, and data all match, the Intent can successfully start the Activity.
  • Action match, Intent can specify 1, or none
  • Category matching rules, Intent can specify 0, 1 or more

- data matching rules.

1. Action matching rules

  • If the action of the Intent matches any of the IntentFilter and an action, the match is successful.
  • If the Intent does not specify an action, the match fails.
  • action is a string, so matching is case sensitive.

2. category matching rules

  • If the Intent has one or more categories, then all categories must be the categories that have been defined in the filtering rules. This is a successful match.
  • If the Intent does not specify a category, the system will add this category to the Intent by default when calling startActivityor .startActivityForResultandroid.intent.category.DEFAULT
  • In order for the activity to receive implicit calls, it must be specified in the intent-filter android.intent.category.DEFAULT.

3. data matching rules

  1. data syntax

    <data android:scheme="string"
          android:host="string"
          android:port="string"
          android:path="string"
          android:pathPattern="string"
          android:pathPrefix="string"
          android:mimeType="string" />
  2. data consists of two parts, mimeType and URI.

    • mimeType: Media type, such as image/jpeg, audio, mpeg4-generic, etc.
    • HATE:
      • structure:<scheme>://<host>:<port>/[<path>|<pathPrefix>|<pathPattern>]
      • Example: content://com.example.project:200/folder/subfolder/etc,http://www.baidu.com:80/search/info
      • scheme: mode, such as http, file, content, etc.
      • Host: The host name.
      • Port: Port number, such as 80.
      • path, pathPrefix, and pathPattern: All represent path information.
        • path: complete path information
        • pathPrefix: The prefix information of the path.
        • pathPattern: full path information, but can contain wildcards "*". In practical applications, escape characters should be added, such as *to write "\\*", \to write "\\\\".
  3. Filter matching rules.

    • Rule: Intent must contain data, and the data data can completely match a certain data in the filtering rule.
    • Example 1:

      • There are filter rules:

        <intent-filter>
            <data android:mimeType="image/* />
            ...
        </intent-filter>

        This rule specifies that the media type is all types of images, and the URI's scheme defaults to content and file.

      • In order to match the above rules, the mimeType attribute must be "image/*", and the scheme of the URI must be content or file. E.g:

        intent.setDataAndType(Uri.parse("file://abc"), "image/png");
      • Warning : If you want to specify the complete data for the Intent, you must call setDataAndTypeit, not first setData, after the call setType, because these two methods will clear each other's values.
    • Example 2:

      • Filter rules exist:

        <intent-filter>
            <data android:mimeType="video/mpeg" android:scheme="http" ... /> 
            <data android:mimeType="audio/mpeg" android:scheme="http" ... />
                        ...
        </intent-filter>
      • Consider the intent to set data to match:

        intent.setDataAndType(Uri.parse("http://abc"), "video/mpeg");

        or

        intent.setDataAndType(Uri.parse("http://abc"), "audio/mpeg");

        can match the above rules.

  4. When an Activity is started implicitly, a judgment should be made to see if there is an Activity that can match our implicit Intent.

    • Use PackageManager, resolveActivityor Intent resolveActivityto find a matching Activity, or return null on failure.
    • Used PackageManagerto querryIntentActivitiesreturn all successfully matched Activities.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325567004&siteId=291194637