"Original" rookie version of Android note 2-activity

Source: Internet
Author: User

1. Activity Introduction

Acitivity is very important in Android development, like JFrame in Java Desktop Development, a controller in the MVC model, typically an application consisting of activities of multiple loosely coupled relationships, An activity is an application component that controls a view that the user can use to interact. Typically, the activity that is presented to the user when the application is first launched is designated as main activity. Each activity can then start another activity in order to complete a different action. Each time an activity starts, the previous activity stops, but the system keeps the activity on a stack. When a new activity is started, it is pushed to the top of the stack to get the user focus. So, when the user finishes the current activity and then clicks the Back button, it is popped up (and destroyed) before the activity resumes. The activity's life cycle is managed by Acitivity Manager.

A. The types of activity are translucent, suspended, full-screen. Translucency, suspension can be achieved by setting theme. The classes it often uses are activity, listactivity, expandablelistactivity.

B. Android, when the application environment changes, the device configuration environment may change (such as screen rotation, keyboard usability changes, language changes). However, when these changes occur, the Android system restarts the activity (OnDestroy () is called, and then OnCreate () is called to create the activity). This is designed to load the resources corresponding to the new configuration environment by reloading the activity so that the activity is well suited to the new configuration environment. Configuration changes cause activity to restart, and you can define android:configchanges to prevent reboots.

C. In order to handle the restart of the activity very well, it should onsaveinstancestate () save its state in the system callback function before the activity is destroyed, and then the system callback function onCreate () when it is rebuilt. Oronrestoreinstancestate (), the corresponding settings are based on the previously saved state.

2. Activity life cycle

In order to be able to play the activity freely, in-depth understanding activity's life cycle is necessary.

Activity from creation to extinction there are several states, active, paused, terminated, inactive.

To facilitate monitoring of changes in these States, the activity provides an event-handling method, and the change in state triggers the activity's corresponding event-handling method.

This picture perfectly interprets the sequence of events.

As you can see from the diagram, there are three lifetimes: full lifetime, visible lifetime, active state lifetime.

The full lifetime is the state from the OnCreate call to the OnDestroy call completion, and sometimes destroy (such as a power outage) is not invoked.

The visible lifetime is the period in which activity can be seen by the user (but not necessarily the focus): from OnStart to OnStop.

An activity lifetime is the period during which activity can interact with the user: from Onresume to OnPause.

A. When activity is created, the first OnCreate method is called, at which point you can call Setcontentview to set the view or viewgroup that the activity displays, that is, the process of initializing the UI and the activity.

B. If the activity was previously run-time pause (also shown), then Onrestoreinstancestate will be called to restore the interface state (from bundle)

C. After the visible lifetime begins, OnStart will be called to start the UI update, which can start threads, broadcastreceiver, sensors, and so on.

D. After that, the active state begins, invoking Onresume, and the interface can interact.

E. When the activity is to be stopped (sometimes, non-active, run-time because of a memory problem stop), the onsaveinstancestate is called, and if the activity is terminated and restarted when it is run, The data that is saved to the bundle is then passed to OnCreate and onrestoreinstancestate. So it's best to oncreate inside to see if it's re-created.

F. When the other activity is started, onpuase is called, and you can suspend UI updates, threads, and CPU-intensive processes that do not need to be updated.

G. When the activity is completely obscured, the onstop is called, and the UI updates, threading and processing, sensors, and broadcastreceiver should be suspended.

H. The end of the life cycle calls OnDestroy and recycles the resources.

I. OnSave is wrong in the picture, most of the cases are after OnPause, onstop ago.

Of course, at the activity level, there is also an event handler function like the one above application.

Event handler function

Onlowmemory

Low memory event trigger, no parameters

Ontrimmemory (int)

Onlowmemory is called when the last background process is killed, the general situation is triggered after the low memory killer kill process, and the Ontrimmemory trigger is more frequent, each time the process priority is evaluated, it is triggered whenever the condition is met.

Onconfigurationchanged (Configuration)

Configuration Change Handling

3. Activity Task and startup mode

In the Android system, the dynamic operation of the activity component is through task, which is a manifestation of component-oriented development, which is much more convenient than the process organization, and the task is to split the connection between components from the details of the process concept. Different activity for the same application is not necessarily in the same task, and the activity of different applications can be in the same task. A task is actually a collection of activity organized in a stack form.

Launchmode

The Launchmode property of the <activity> element can be set to four different loading modes:

A. Standard (default mode): Pushes the active activity at the top of the current caller's task stack.

B. Singletop: Basically consistent with the standard, only when the requested activity is located at the top of the stack, there is a difference. At this point, the activity configured as Singletop no longer constructs a new instance into the task stack, but instead sends the new intent to the top of the stack activity, and the activity at the top of the stack can handle the new intent by overloading the onnewintent.

C. Singletask: Separate task. The activity marked as Singletask, at most one instance exists, and is located in the task with which it is rooted. All requests for the activity are skipped to the activity's task. However, you need to set up a separate taskaffinity for Singletask.

D. SingleInstance: Separate task. Most of the time singleinstance and Singletask are exactly the same, the only difference being that the activity of singleinstance is the only activity in its stack, and if other activity is involved, are transferred to other tasks.

Taskaffinity

The taskaffinity attribute of the <activity> element that represents kinship, which tends to be the same activity as the taskaffinity attribute, Thrown into the same task (even if the activity of a different application). However, its binding force is much weaker than that of Launchmode. Only the allowtaskreparenting is set to true, or the caller adds the intent FLAG to the Flag_activity_new_task attribute when it takes effect. If the activity's android:taskaffinity is not configured in manifest, each activity uses the same taskaffinity as application, which means that The taskaffinity of all activity in the same application is the same by default.

Example:

A Two activity:mainactivity and subactivity, start mainactivity,mainactivity start subactivity First, subactivity start subactivity. Standard mode. The final task stack is shown below.

B Two activity:mainactivity and Subactivitysingletop, first start the mainactivity,mainactivity to start the subactivitysingletop of single top mode, Subactivitysingletop start single top mode subactivitysingletop. The final task stack is shown below.

C Two activity:mainactivity and Subactivitysingletask, start the subactivitysingletask of the single task mode first mainactivity,mainactivity , Subactivitysingletask launches single task mode subactivitysingletask. Note that the subactivitysingletask is started two times. The final task stack is shown below.

From this figure, this is the same as Singletop's performance, why? Look underneath.

D Two activity:mainactivity and Subactivityrealsingletask, start mainactivity,mainactivity start single Task mode Subactivityrealsingletask, Subactivityrealsingletask launches single task mode subactivitysingletask. Note that the subactivityrealsingletask is started two times. Unlike C, this time I set up an independent taskaffinity the final task stack is shown below.

Luo Shenyang Blog, said: "

1. set "Singletask" Activity in startup mode, which, when started, looks for property values in the system Affinity equals its property value taskaffinity The task for exists, and if such a task exists, it will start in the task or it will start in a new task. So, if we want to set the "Singletask" startup mode Activity starts in a new task, it is necessary to set a separate taskaffinity The property value.

2. if the Activity that has the "Singletask" startup mode set is not started in a new task, It will see if there is a corresponding activity Instance in the existing task, and if it does, it will be the one on the activity Instance Activity all over, that's the end. Activity The instance is located at the top of the task's stack.

E. Three activity:mainactivity, Subactivityrealsingletask (single task, set affinity) and Subactivityinter, start mainactivity First, Mainactivity start Subactivityrealsingletask, subactivityrealsingletask start Standard mode subactivityinter. Then:

Then Subactivityinter started the subactivityrealsingletask. The final task stack is shown below.

F. Three activity:mainactivity (single top), Subactivitysingleinstance (one intantce, Affinity) and SubActivityInter2 (standard) are not set. Mainactivity start Subactivitysingleinstance first. Picture below

Subactivitysingleinstance start SubActivityInter2, as follows

SubActivityInter2 Start mainactivity

Note: If Launchmode is set to standard,affinity, it is not valid.

Intent Flags : (Start Activity use), this very pit

FLAG

Explain

Flag_activity_new_task

With this flag set, the new start activity will be placed in a new task

Flag_activity_clear_top

Activity to start if it already exists in the current task, erase all activity above

Flag_activity_single_top

Similar to single top

Wait, wait.

Task cleanup

If a user leaves a task for a long time, the system cleans up all activity in the task except the root activity. However, you can control this behavior with the activity following properties:

Alwaysretaintaskstate

Always keep the task status. If this property is set to "true" in the root activity of a task, the above default behavior does not occur. The task retains all activity within its stack for a long period of time.

Cleartaskonlaunch

Each time the task is emptied, leaving only the root activity. If this property is set to "true" in the root activity of a task, each time the user leaves the task and returns it, the stack is emptied to leave only the root activity. This happened to be contrary to alwaysretaintaskstate.

Finishontasklaunch

Only for a single activity, not an entire task. And it can make any activity be cleaned up, even the root activity is no exception. When it is set to "true", as long as it leaves the task stack, the system clears the activity immediately, regardless of where the activity is on the stack.

Task stacks to use with each parameter

4. Switching of activity

A. Direct call, do not need to know the result, adopt startactivity

B. Call directly, need to know the result, take Startactivityforresult (), and overload the Onactivityresult method. It is more important to note that when the user presses the back key, the system will resultcode to result_canceled, unable to pass the data.

Intent result = new Intent ("Com.example.RESULT_ACTION", Uri.parse ("Content://result_uri");

Setresult (ACTIVITY.RESULT_OK, RESULT);

Finish ();

5. Activity System Scheduling

Activity scheduling relies on the activity Manager Service in the Android framework. The framework framework uses C/s to implement a background service activitymanagerservice to manage specific acitivity instances.

Mainactivity Start-up process (root activity)

A. The launcher component wants to activitymanagerservice send an inter-process communication request that initiates the mainactivity component. (Binder)

B. Activitymanagerservice the Mainactivity component information to be started first, and then sends an interprocess communication request (Binder) into the abort state like the launcher component.

C. After the launcher component enters the abort state, it reports to Activitymanagerservice that its abort status has entered. Then Activitymanagerservice resumes execution of the startup mainactivity.

D. Activitymanagerservice discovers that the process running the Mainactivity component does not exist and that he will start a process.

E. When the new process starts, it sends a start-up communication to Activitymanagerservice, Activitymanagerservice continues the startup action.

F. Activitymanagerservice sends the information for the second-step saved mainactivity component to the new process, allowing him to launch the Mainactivity component. Each component is a taskrecord.

Sub-component start-up process

A. The Mainactivity component sends an inter-process communication request to activitymanagerservice that initiates the subactivity.

B. Activitymanagerservice saves the subactivity information and sends a request to mainactivity for interprocess communication to the terminating state.

C. After the mainactivity enters the abort state, the Binder report has entered the abort state to Activitymanagerservice. Activitymanagerservice continues execution of the boot.

D. A discovers that the process running the sub already exists, then sends the subactivity information to that process, and that process starts the component.

Android application process creation relies heavily on the zygote process (zygote is the meaning of a fertilized egg ), and the zygote process has a virtual machine instance inside, so zygote can quickly create a virtual machine sample by replicating itself. Each application process that is created has a virtual machine (used to execute the component), a binder thread pool, and a message loop (interprocess communication).

Original, reprint annotated source OH: http://www.cnblogs.com/stonehat/p/5947678.html

"Original" rookie version of Android note 2-activity

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.