Android development activity details

Source: Internet
Author: User

This article mainly describes the application lifecycle, activity lifecycle, and intent application in the activity.

I. Application Lifecycle

Unlike most traditional operating system environments, Android applications cannot control their own lifecycles. So the various components of the application (activity, service ......) You must always be careful about the impact of application status changes on them to prevent them from being terminated at an inappropriate time.

In Android, each application has an independent process running on an independent Dalvik (Android-specific virtual machine ). Process Management and memory management during running of each application are relatively independent. Android uses an "intrusive" method to manage system resources, which means that in order to release resources to high-priority programs (usually programs that are directly interacting with users ), some processes and their host programs will end relentlessly without any warning.

Understanding application priority and Process status

Some processes are terminated to release and Recycle resources. What processes will be terminated? Is a ended first or B ended first? This is determined by the priority of the Host application. An application has the same priority as a component with the highest priority. If the two programs have the same priority at the moment, the process that has been in the lower priority for a long time will be terminated. The priority of a process is affected by the attach relationship between processes. For example, if the service or content provider that application a depends on is provided by application B, application B has a higher priority. All Android applications are left to run in the memory until the system needs to release and Recycle resources. Various processes and their corresponding priorities.

Activity ProcessAn active process is a component that the Host Program interacts with directly. Android tries to recycle various resources to ensure its running status. A small number of such processes are usually terminated.

The active process includes the following types:

  • Activity is active, that is, in foreground, and receives response to user events
  • Activities, services, or broadcast receivers is executing onreceive event processing
  • Services is processing onstart, oncreate, or ondestroy events

Visible ProcessActivity that is visualized but not in the active state. They are neither in foreground nor accept responses to user events. This happens when some of the activities are overwritten (for example, we click a button in a to bring up a dialog, and then a becomes a visible process ). There are also few visible processes. In extreme cases, to ensure that the running of the activity process is terminated.

Started service processNote that the service process is started. The service process needs to run continuously without a visual interface, because the service does not directly interact with the user. They are still considered as front-end processes and will only end when visible and activity process need resources.

Background ProcessA process that is affiliated to an invisible activity and does not start any service process becomes a background process. Generally, there are a lot of background processes in Android. Android uses the last-seen-first-killed method to end such processes and provide resources for the foreground process.

Empty ProcessTo improve the performance of the entire system, Android retains the end-of-life applications in the memory. Android retains these caches so that the application can be started quickly. They will be terminated as usual.

To sum up, it is very important to properly organize applications to ensure stable operation and prevent termination of the operation.

Ii. Activity Lifecycle

Correct understanding of the lifecycle of an activity is very important. Only by correctly understanding the lifecycle of an activity can the application provide a logical user experience and correctly manage the resources of the application. Android applications cannot manage their own lifecycles, but are managed by the system in a unified manner. Of course, the same is true for activity. The activity State determines the priority of the application when the activity process is managed and whether the activity process is terminated. In turn, the priority of the program also affects whether the activity will be terminated during running and whether the activity will continue to run.

1. Activity Stack

The position of the activity in the stack determines the activity status. When a new activity starts, it will be regarded as a foreground screen and placed on the top of the stack. When a user triggers a "return" event or a foreground activity is closed, the next activity is moved to the top of the stack and activated. As shown in:
















As mentioned before, the priority of an application in Android is determined by the component with the highest priority (generally activity. Therefore, when Android needs to terminate some applications to release system resources, it determines the application priority based on the activity stack, so as to terminate those applications with lower priority.

2. Activity Status

  • ActivateWhen an activity is at the top of the active stack, it is visible, focused, and user input is acceptable. Android will try to recycle resources at any cost, or even terminate the activity at the bottom of the stack, to ensure the demand for resources in the activity at the top of the stack. When a new activity is activated, the activity will be suspended or stopped.
  • PauseThe activity is visible, but cannot be focused. The activity is paused. User events cannot be accepted when the activity is paused. In extreme cases, Android terminates a paused activity to recycle system resources. When an activity is completely overwritten, it is in the stopped state.
  • StopWhen an activity is invisible, it is stopped. The activity retains the status and component information in the memory. When an activity is in the stopped status, we need to save the data and UI status. When an activity is closed or exited, it enters the inactive state.
  • No activity (sleep)After the activity is disabled, the activity is not active before it is restarted. The activity in this status does not exist in the activity stack. You need to restart the activity before it is displayed and used.

Changes to the activity status are uncertain, which is completely controlled by the android Memory Manager. Android disables applications that are in sleep, stopped, or even paused state. In order to provide a good user experience, changes to the activity status should be transparent to users, so when the activity enters the pause and stop status, it is very important to save the UI status and persistent data. Once the activity is re-activated, relevant data is restored.

3. monitoring activity status changes

To ensure a correct response to activity status changes, Android provides a series of event controllers that listen to activity status changes throughout the lifecycle. The lifecycle of an activity can be further refined into: full life cycle> visible life cycle> active life cycle, as shown in:











As shown in, changes to activity status will trigger the corresponding method.

Full lifetimeThe entire cycle is between calling oncreate and ondestroy. In some cases, terminating an activity does not call ondestroy. Activity initializes user interfaces, Data, starts services, and threads by calling oncreate. The oncreate method has a bundle object parameter, which contains the UI State data that was last called to save onsaveintancestate. We can use this parameter in oncreate to restore the UI State data or override onrestoreinstancestate. Override ondestroy to release resources and close databases.

To write more efficient code, we recommend that you avoid creating short-term objects. The rapid creation and destruction of objects can easily increase the stress on the fragment thread, which will directly affect the user experience.

Visible lifetimeThe visible period is between calling onstart and onstop. In this case, the activity is visible, but cannot respond to user events. An activity may experience multiple visual periods in its lifecycle. In extreme cases, the system may also terminate a visible activity, which is rare. The onstop method is usually used to temporarily or stop animations, threads, timers, and services used to update the UI. Therefore, when activity is invisible, very few system resources are occupied. When the activity changes from invisible to visible, start related threads and services in onstart. Onstart and onstop are also used to register and cancel registration (unregister) broadcast recipients used to update the UI. When the activity is invisible, We need to cancel the receivers, especially those that support the intent action (intent) and updated the UI.

Activity lifetimeWhen the onresume of the activity is called, the activity enters the activation period. When onpause is called, the activation period ends. When an activity is activated, it will be on the foreground screen and respond to user events. There are also multiple activation periods before the activity lifecycle ends. Once a new activity is activated, the current activity will lose focus (pause or even stop ......). The activation period is an active part of the activity lifecycle, and onresume and onpause are frequently called. Therefore, in order to have a good user experience, the code in the onresume and onpause methods must be more efficient.

Before onpause is called, the activity will call onsaveinstancestate to save the UI status of the activity to bundle. This bundle is the parameter of the oncreate and onrestoreinstancestate methods. Onsaveinstancestate: saves the UI status (for example, the status of multiple buttons and the UI focus =). In this way, the UI before suspension can be correctly displayed when the activity is re-activated. Most activities rewrite the onpause method to submit unsaved data. We can also choose whether to suspend the thread and broadcast receiver, depending on the software architecture. Generally, onresume does not execute too much code. Creating a UI is generally implemented in oncreate or onrestoreinstancestate.

Iii. Intent

Intent Chinese meaning is the purpose. Android also means "purpose. This is where we are going. Intent is needed to go from this activity to another activity.

Sample Code 1:

// Define an intent

Intent intent = new intent (intentdemo. This, anotheractivity2.class );

// Start the activity

Startactivity (intent );

The preceding sample code is used to switch from intentdemo activity to anotheractivity2. This is one of intent constructor methods, specifying two activities. Why do we need to specify two activities? Because there is an active stack in Android, this construction method can ensure that the previous activity is correctly pushed into the stack, and the activity can correctly exit the stack when the return key is triggered.

Note: all activities must be declared in androidmanifest. xml. The following is the program configuration file used in this article.

<? XML version = "1.0" encoding = "UTF-8"?>

<Manifest xmlns: Android = ""

Package = "com. halzhang. Android. intent" Android: versioncode = "1"

Android: versionname = "1.0" type = "codeph" text = "/codeph">

<Application Android: icon = "@ drawable/icon" Android: Label = "@ string/app_name">

<Activity Android: Name = ". intentdemo" Android: Label = "@ string/app_name">


<Action Android: Name = "android. Intent. Action. Main"/>

<Category Android: Name = "android. Intent. Category. launcher"/>



<Activity Android: Name = ". anotheractivity" Android: Label = "another">


<Action Android: Name = "android. Intent. Action. Edit"/>

<! -- Category must be configured; otherwise, an error occurs: activity cannot be found -->

<Category Android: Name = "android. Intent. Category. Default"/>




<Activity Android: Name = ". anotheractivity2" Android: Label = "another2">


<Action Android: Name = "android. Intent. Action. Edit"/>

<Category Android: Name = "android. Intent. Category. Default"/>




<Uses-SDK Android: minsdkversion = "3"/>

<! --

The two activities configured above have the same action type, all of which are "android. Intent. Action. Edit"

When the action attribute of intent is intent. action_edit, the system does not know which activity to switch,

A dialog will pop up listing all actions as "android. Intent. Action. Edit"

Activity for users



1. Intent Constructor

Common constructor:

1. Intent () null Constructor

2. Intent (intent O) copy constructor

3. Intent (string action) specifies the constructor of the action type.

4. Intent (string action, Uri URI) specifies the action type and Uri constructor. Uri is mainly used in combination with data sharing between programs. contentprovider

5. Intent (context packagecontext, class <?> CLs) input component constructor, that is, the aforementioned

6. Intent (string action, Uri, context packagecontext, class <?> CLs) the first two combinations

Intent has six constructor types. 3, 4, and 5 are the most commonly used and are not useless!

The action of Intent (string action, Uri URI) is the name attribute value corresponding to the Action node in androidmainfest. xml. Many action and category constants are defined in the intent class.

Sample Code 2:

1: intent = new intent (intent. action_edit, null );

2: startactivity (intent );

The second example uses the fourth constructor, but the URI parameter is null. When this code is executed, the system will find it in the main configuration file androidmainfest. xml.

<Action Android: Name = "android. intent. action. edit "/> corresponding activity. If multiple activities have <action Android: Name =" android. intent. action. edit "/> A dailog selection activity will pop up, as shown in the right figure:

This is not the case if the sample code is used for sending.

2. Use intent to transmit data between activities

Run the following code in main:

Bundle bundle = new bundle ();

Bundle. putstringarray ("namearr", namearr );

Intent intent = new intent (main. This, countlist. Class );

Intent. putextras (bundle );

Startactivity (intent );

In countlist, the Code is as follows:

Bundle bundle = This. getintent (). getextras ();

String [] arrname = bundle. getstringarray ("namearr ");

The above code implements data transmission between activities!

Related Article

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: 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.