# Application Fundamentals——应用程序基础知识

## Key classes——关键类

1. Activity 
2. Service 
3. BroadcastReceiver 
4. ContentProvider 
5. Intent 

## In this document——在这篇文章中

Android applications are written in the Java programming language. The compiled Java code — along with any data and resource files required by the application — is bundled by the aapt  tool  into an Android package , an archive file marked by an .apk  suffix. This file is the vehicle for distributing the application and installing it on mobile devices; it's the file users download to their devices. All the code in a single .apk  file is considered to be one application .
Android应用程序是用Java编程语言编写的。 编译好的Java代码——随同所有应用程序要使用的数据和资源文件一起——使用 aapt  tool 打包成一个Android包，即一个后缀为 .apk 的归档文件。此文件是发布应用程序和在移动设备上安装应用程序的有媒介；它是用户下载到他们设备上的文件。 在一个.apk文件中的所有代码被认为是一个应用程序。

In many ways, each Android application lives in its own world:

• By default, every application runs in its own Linux process. Android starts the process when any of the application's code needs to be executed, and shuts down the process when it's no longer needed and system resources are required by other applications.     默认的，每一个程序运行在其自己的Linux进程中。Android在应用程序中某段代码需要被执行时启动一个进程，不再使用或系统资源被其他应用程序请 求时关闭这个进程。
• Each process has its own Java virtual machine (VM), so application code runs in isolation from the code of all other applications.     每一个进程都有自己的Java虚拟机（VM），一个应用程序代码运行时同其他程序代码分开，不受任何其他程序的代码的影响。
• By default, each application is assigned a unique Linux user ID. Permissions are set so that the application's files are visible only that user, only to the application itself — although there are ways to export them to other applications as well.     默认的，每个应用程序享有一个独自的Linux用户ID。由于权限设定原因，一个应用程序的文件只有本用户（其自己）可见——当然，也有把他们导出给其他 应用程序的机制。

It's possible to arrange for two applications to share the same user ID, in which case they will be able to see each other's files. To conserve system resources, applications with the same ID can also arrange to run in the same Linux process, sharing the same VM.

## Application Components——应用程序组件

A central feature of Android is that one application can make use of elements of other applications (provided those applications permit it). For example, if your application needs to display a scrolling list of images and another application has developed a suitable scroller and made it available to others, you can call upon that scroller to do the work, rather than develop your own. Your application doesn't incorporate the code of the other application or link to it. Rather, it simply starts up that piece of the other application when the need arises.
Android的一个中心功能就是应用程序可以使用其他应用程序的元素（在提供元素的应用程序允许的情况下）。例如，如果您的应用 程序想要显示一系列带有滑屏效果功能的图片，然后某个应用程序正巧开发出了合适的滑屏的模块，并且同意共享，您就可以调用哪个滑屏模块处理这些图片并显示 出来，而不是您自己再去开发一个。您的应用程序并没有包含或链接到了其他的应用程序的代码。但是当请求发出后，您的应用程序确实可以简单的使用其他程序的 部分功能。

For this to work, the system must be able to start an application process when any part of it is needed, and instantiate the Java objects for that part. Therefore, unlike applications on most other systems, Android applications don't have a single entry point for everything in the application (no main()  function, for example). Rather, they have essentialcomponents  that the system can instantiate and run as needed. There are four types of components:

Activities——活动
An activity  presents a visual user interface for one focused endeavor the user can undertake. For example, an activity might present a list of menu items users can choose from or it might display photographs along with their captions. A text messaging application might have one activity that shows a list of contacts to send messages to, a second activity to write the message to the chosen contact, and other activities to review old messages or change settings. Though they work together to form a cohesive user interface, each activity is independent of the others. Each one is implemented as a subclass of the Activity   base class.

An application might consist of just one activity or, like the text messaging application just mentioned, it may contain several. What the activities are, and how many there are depends, of course, on the application and its design. Typically, one of the activities is marked as the first one that should be presented to the user when the application is launched. Moving from one activity to another is accomplished by having the current activity start the next one.

Each activity is given a default window to draw in. Typically, the window fills the screen, but it might be smaller than the screen and float on top of other windows. An activity can also make use of additional windows — for example, a pop-up dialog that calls for a user response in the midst of the activity, or a window that presents users with vital information when they select a particular item on-screen.

The visual content of the window is provided by a hierarchy of views — objects derived from the base View   class. Each view controls a particular rectangular space within the window. Parent views contain and organize the layout of their children. Leaf views (those at the bottom of the hierarchy) draw in the rectangles they control and respond to user actions directed at that space. Thus, views are where the activity's interaction with the user takes place. For example, a view might display a small image and initiate an action when the user taps that image. Android has a number of ready-made views that you can use — including buttons, text fields, scroll bars, menu items, check boxes, and more.

A view hierarchy is placed within an activity's window by the Activity.setContentView()   method. The content view  is the View object at the root of the hierarchy. (See the separate User Interface  document for more information on views and the hierarchy.)

Services——服务
service  doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it. Each service extends the Service   base class.

A prime example is a media player playing songs from a play list. The player application would probably have one or more activities that allow the user to choose songs and start playing them. However, the music playback itself would not be handled by an activity because users will expect the music to keep playing even after they leave the player and begin something different. To keep the music going, the media player activity could start a service to run in the background. The system would then keep the music playback service running even after the activity that started it leaves the screen.

It's possible to connect to (bind to) an ongoing service (and start the service if it's not already running). While connected, you can communicate with the service through an interface that the service exposes. For the music service, this interface might allow users to pause, rewind, stop, and restart the playback.

Like activities and the other components, services run in the main thread of the application process. So that they won't block other components or the user interface, they often spawn another thread for time-consuming tasks (like music playback). See Processes and Threads , later.

broadcast receiver  is a component that does nothing but receive and react to broadcast announcements. Many broadcasts originate in system code — for example, announcements that the timezone has changed, that the battery is low, that a picture has been taken, or that the user changed a language preference. Applications can also initiate broadcasts — for example, to let other applications know that some data has been downloaded to the device and is available for them to use.

An application can have any number of broadcast receivers to respond to any announcements it considers important. All receivers extend the BroadcastReceiver   base class.

Broadcast receivers do not display a user interface. However, they may start an activity in response to the information they receive, or they may use the  BroadcastReceiver  to alert the user. Notifications can get the user's attention in various ways — flashing the backlight, vibrating the device, playing a sound, and so on. They typically place a persistent icon in the status bar, which users can open to get the message.

Content providers——内容提供者
content provider  makes a specific set of the application's data available to other applications. The data can be stored in the file system, in an SQLite database, or in any other manner that makes sense. The content provider extends the ContentProvider   base class to implement a standard set of methods that enable other applications to retrieve and store data of the type it controls. However, applications do not call these methods directly. Rather they use aContentResolver   object and call its methods instead. A ContentResolver can talk to any content provider; it cooperates with the provider to manage any interprocess communication that's involved.
content provider  使程序中特定的数据可被其他程序使用。共享的数据可以存储在文件系统中、SQLite数据库中或其他任何可用的介质。内容提供者由ContentProvider 基类派生，实现了一系列的   使其他程序获取和存储其支持的数据格式的   方法。但是应用程序不会直接调用这些方法。而是使用ContentResolver 对象，然后调用这个对象的方法。ContentResolver能与任何内容提供者对话，它与提供者合作来管理所有涉及到的进程间通信。

See the separate Content Providers  document for more information on using content providers.

Whenever there's a request that should be handled by a particular component, Android makes sure that the application process of the component is running, starting it if necessary, and that an appropriate instance of the component is available, creating the instance if necessary.

### Activating components: intents——激活别的组件的组件：意图

Content providers are activated when they're targeted by a request from a ContentResolver. The other three components — activities, services, and broadcast receivers — are activated by asynchronous messages called intents . An intent is an Intent   object that holds the content of the message. For activities and services, it names the action being requested and specifies the URI of the data to act on, among other things. For example, it might convey a request for an activity to present an image to the user or let the user edit some text. For broadcast receivers, the Intent object names the action being announced. For example, it might announce to interested parties that the camera button has been pressed.

There are separate methods for activiating each type of component:

• An activity is launched (or given something new to do) by passing an Intent object to Context.startActivity()   or Activity.startActivityForResult()  . The responding activity can look at the initial intent that caused it to be launched by calling its getIntent()   method. Android calls the activity's onNewIntent()   method to pass it any subsequent intents.          向 Context.startActivity() Activity.startActivityForResult() 传递Intent对象可以激活（或获得新的任务）一个活动。响应的活动可以通过调用 getIntent() 方法查看导致自己被激活的最初的意图。Android调用活动的 onNewIntent() 方法来传递之后的意图。

One activity often starts the next one. If it expects a result back from the activity it's starting, it calls startActivityForResult()  instead of startActivity() . For example, if it starts an activity that lets the user pick a photo, it might expect to be returned the chosen photo. The result is returned in an Intent object that's passed to the calling activity's onActivityResult()   method.        一个活动通常会开启另一个活动。如果前一个活动希望从新启动的活动获得一个运行结果，可以调用startActivityForResult() 方法来代替startActivity() 方法。例如，如果一个老活动开启了一个让用户照相的新活动，又希望从新活动获得这张照片。新活动的运行结果是通过一个   传递给老活动的 onActivityResult() 方法的   Intent对象传递的。

• A service is started (or new instructions are given to an ongoing service) by passing an Intent object to Context.startService()  . Android calls the service's onStart()   method and passes it the Intent object.

Similarly, an intent can be passed to Context.bindService()   to establish an ongoing connection between the calling component and a target service. The service receives the Intent object in an onBind()   call. (If the service is not already running, bindService()  can optionally start it.) For example, an activity might establish a connection with the music playback service mentioned earlier so that it can provide the user with the means (a user interface) for controlling the playback. The activity would call bindService()  to set up that connection, and then call methods defined by the service to affect the playback.        服务通过向 Context.startService() 传递一个Intent对象启动（或给予新任务）Android调用服务的 onStart() 方法然后将Intent对象传递给服务。类似的，一个意图可以被传给 Context.bindService() 来建立呼叫组件和被叫组件的实时连接。调用服务的 onBind() 来使其接受Intent对象。（如果服务未在运行，您可以选择使用bindService() 来启动它。）例如上面提到过的音乐播放服务，活动会希望建立一个与此服务的连接以向用户提供控制播放的功能（例如一个UI界面）。这时活动就会调用bindService() 来建立连接，然后调用服务中定义的方法来控制播放。

• A later section, Remote procedure calls , has more details about binding to a service.          之后的章节会讲到Remote procedure calls ，那有更详细的绑定服务的信息。

• An application can initiate a broadcast by passing an Intent object to methods like Context.sendBroadcast() Context.sendOrderedBroadcast()  , and Context.sendStickyBroadcast()   in any of their variations. Android delivers the intent to all interested broadcast receivers by calling their onReceive()   methods.          程序可以通过向类似    Context.sendBroadcast() Context.sendOrderedBroadcast() Context.sendStickyBroadcast() ，及它们的变种   的方法传递一个Intent对象来初始化一条广播。

For more on intent messages, see the separate article, Intents and Intent Filters .

### Shutting down components——关闭组件

A content provider is active only while it's responding to a request from a ContentResolver. And a broadcast receiver is active only while it's responding to a broadcast message. So there's no need to explicitly shut down these components.

Activities, on the other hand, provide the user interface. They're in a long-running conversation with the user and may remain active, even when idle, as long as the conversation continues. Similarly, services may also remain running for a long time. So Android has methods to shut down activities and services in an orderly way:

• An activity can be shut down by calling its finish()   method. One activity can shut down another activity (one it started with startActivityForResult() ) by calling finishActivity()  .

• A service can be stopped by calling its stopSelf()   method, or by calling Context.stopService()  .

Components might also be shut down by the system when they are no longer being used or when Android must reclaim memory for more active components. A later section, Component Lifecycles , discusses this possibility and its ramifications in more detail.

### The manifest file——清单文件

Before Android can start an application component, it must learn that the component exists. Therefore, applications declare their components in a manifest file that's bundled into the Android package, the .apk  file that also holds the application's code, files, and resources.

Android启动一个新的应用程序组件之前，他必须知道这个组件确实存在。因此，应用程序在清单文件中声明了他的全部组件。清单文件随同应用程序的代码、文件、资源一同打包在了Android包中，即.apk 文件中。

The manifest is a structured XML file and is always named AndroidManifest.xml for all applications. It does a number of things in addition to declaring the application's components, such as naming any libraries the application needs to be linked against (besides the default Android library) and identifying any permissions the application expects to be granted.

But the principal task of the manifest is to inform Android about the application's components. For example, an activity might be declared as follows:

<?xml version="1.0" encoding="utf-8"?>
<manifest . . . >
<application . . . >
<activity android:name="com.example.project.FreneticActivity"
android:icon="@drawable/small_pic.png"
android:label="@string/freneticLabel"
. . .  >
</activity>
. . .
</application>
</manifest>

The name  attribute of the <activity>   element names the Activity   subclass that implements the activity. The icon  and label  attributes point to resource files containing an icon and label that can be displayed to users to represent the activity.

<activity>  元素的name 属性命名了实现了activity的Activity  子类。iconlabel 属性指向了   包含被显示给用户来代表这个活动的图标和标题   的文件。

The other components are declared in a similar way — <service>   elements for services, <receiver>   elements for broadcast receivers, and <provider>   elements for content providers. Activities, services, and content providers that are not declared in the manifest are not visible to the system and are consequently never run. However, broadcast receivers can either be declared in the manifest, or they can be created dynamically in code (as BroadcastReceiver   objects) and registered with the system by calling Context.registerReceiver()  .

For more on how to structure a manifest file for your application, see The AndroidManifest.xml File .

### Intent filters——意图匹配器

An Intent object can explicitly name a target component. If it does, Android finds that component (based on the declarations in the manifest file) and activates it. But if a target is not explicitly named, Android must locate the best component to respond to the intent. It does so by comparing the Intent object to the intent filters  of potential targets. A component's intent filters inform Android of the kinds of intents the component is able to handle. Like other essential information about the component, they're declared in the manifest file. Here's an extension of the previous example that adds two intent filters to the activity:
Intent对象会详细地指明一个目标组件。Android会找到那个组件（根据清单文件中的 声明）然后激活它。但是如果目标没有被明确指出， Android就必须找到能响应这个意图的最佳组件。Android将Intent对象和可能的目标组件的意图匹配器进行比较来找出这个最佳组件。组件的 意图匹配器告诉Android这个组件能操作什么样的意图。就像组件的其他重要信息一样，它们声明于清单文件中。这里是上边那个例子的增扩版，向活动中添 加了两个意图匹配器。

<?xml version="1.0" encoding="utf-8"?>
<manifest . . . >
<application . . . >
<activity android:name="com.example.project.FreneticActivity"
android:icon="@drawable/small_pic.png"
android:label="@string/freneticLabel"
. . .  >
<intent-filter . . . >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter . . . >
<action android:name="com.example.project.BOUNCE" />
<data android:mimeType="image/jpeg" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
. . .
</application>
</manifest>

The first filter in the example — the combination of the action "android.intent.action.MAIN " and the category "android.intent.category.LAUNCHER " — is a common one. It marks the activity as one that should be represented in the application launcher, the screen listing applications users can launch on the device. In other words, the activity is the entry point for the application, the initial one users would see when they choose the application in the launcher.

The second filter declares an action that the activity can perform on a particular type of data.

A component can have any number of intent filters, each one declaring a different set of capabilities. If it doesn't have any filters, it can be activated only by intents that explicitly name the component as the target.

For a broadcast receiver that's created and registered in code, the intent filter is instantiated directly as an IntentFilter   object. All other filters are set up in the manifest.

For more on intent filters, see a separate document, Intents and Intent Filters .

As noted earlier, one activity can start another, including one defined in a different application. Suppose, for example, that you'd like to let users display a street map of some location. There's already an activity that can do that, so all your activity needs to do is put together an Intent object with the required information and pass it to startActivity() . The map viewer will display the map. When the user hits the BACK key, your activity will reappear on screen.

To the user, it will seem as if the map viewer is part of the same application as your activity, even though it's defined in another application and runs in that application's process. Android maintains this user experience by keeping both activities in the same task . Simply put, a task is what the user experiences as an "application." It's a group of related activities, arranged in a stack. The root activity in the stack is the one that began the task — typically, it's an activity the user selected in the application launcher. The activity at the top of the stack is one that's currently running — the one that is the focus for user actions. When one activity starts another, the new activity is pushed on the stack; it becomes the running activity. The previous activity remains in the stack. When the user presses the BACK key, the current activity is popped from the stack, and the previous one resumes as the running activity.

The stack contains objects, so if a task has more than one instance of the same Activity subclass open — multiple map viewers, for example — the stack has a separate entry for each instance. Activities in the stack are never rearranged, only pushed and popped.

A task is a stack of activities, not a class or an element in the manifest file. So there's no way to set values for a task independently of its activities. Values for the task as a whole are set in the root activity. For example, the next section will talk about the "affinity of a task"; that value is read from the affinity set for the task's root activity.

All the activities in a task move together as a unit. The entire task (the entire activity stack) can be brought to the foreground or sent to the background. Suppose, for instance, that the current task has four activities in its stack — three under the current activity. The user presses the HOME key, goes to the application launcher, and selects a new application (actually, a new task ). The current task goes into the background and the root activity for the new task is displayed. Then, after a short period, the user goes back to the home screen and again selects the previous application (the previous task). That task, with all four activities in the stack, comes forward. When the user presses the BACK key, the screen does not display the activity the user just left (the root activity of the previous task). Rather, the activity on the top of the stack is removed and the previous activity in the same task is displayed.

The behavior just described is the default behavior for activities and tasks. But there are ways to modify almost all aspects of it. The association of activities with tasks, and the behavior of an activity within a task, is controlled by the interaction between flags set in the Intent object that started the activity and attributes set in the activity's <activity>   element in the manifest. Both requester and respondent have a say in what happens.

In this regard, the principal Intent flags are:

FLAG_ACTIVITY_NEW_TASK
FLAG_ACTIVITY_CLEAR_TOP
FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
FLAG_ACTIVITY_SINGLE_TOP

The principal <activity>  attributes are:

taskAffinity
launchMode
allowTaskReparenting
clearTaskOnLaunch
alwaysRetainTaskState
finishOnTaskLaunch

The following sections describe what some of these flags and attributes do, how they interact, and what considerations should govern their use.

By default, all the activities in an application have an affinity  for each other — that is, there's a preference for them all to belong to the same task. However, an individual affinity can be set for each activity with the taskAffinity  attribute of the <activity>  element. Activities defined in different applications can share an affinity, or activities defined in the same application can be assigned different affinities. The affinity comes into play in two circumstances: When the Intent object that launches an activity contains the FLAG_ACTIVITY_NEW_TASK  flag, and when an activity has its allowTaskReparenting  attribute set to "true ".

The FLAG_ACTIVITY_NEW_TASK   flag——FLAG_ACTIVITY_NEW_TASK  控制标
As described earlier, a new activity is, by default, launched into the task of the activity that called startActivity() . It's pushed onto the same stack as the caller. However, if the Intent object passed to startActivity()  contains theFLAG_ACTIVITY_NEW_TASK  flag, the system looks for a different task to house the new activity. Often, as the name of the flag implies, it's a new task. However, it doesn't have to be. If there's already an existing task with the same affinity as the new activity, the activity is launched into that task. If not, it begins a new task.

The allowTaskReparenting   attribute——allowTaskReparenting  属性
If an activity has its allowTaskReparenting  attribute set to "true ", it can move from the task it starts in to the task it has an affinity for when that task comes to the fore. For example, suppose that an activity that reports weather conditions in selected cities is defined as part of a travel application. It has the same affinity as other activities in the same application (the default affinity) and it allows reparenting. One of your activities starts the weather reporter, so it initially belongs to the same task as your activity. However, when the travel application next comes forward, the weather reporter will be reassigned to and displayed with that task.

If an .apk  file contains more than one "application" from the user's point of view, you will probably want to assign different affinities to the activities associated with each of them.

### Launch modes——启动模式

There are four different launch modes that can be assigned to an <activity>  element's launchMode   attribute:

"standard " (the default mode) ——标准（默认的）
"singleTop
"singleTask
"singleInstance "

The modes differ from each other on these four points:

• Which task will hold the activity that responds to the intent . For the "standard " and "singleTop " modes, it's the task that originated the intent (and called startActivity()  ) — unless the Intent object contains theFLAG_ACTIVITY_NEW_TASK   flag. In that case, a different task is chosen as described in the previous section, Affinities and new tasks
响应意图的活动会被装入哪个任务。 "standard "和"singleTop "模式，是装入发出意图（调用了startActivity()  ）的任务——除非Intent对象含有FLAG_ACTIVITY_NEW_TASK  控制标。后种情况流程如前边Affinities and new tasks 章节所述。

In contrast, the "singleTask " and "singleInstance " modes mark activities that are always at the root of a task. They define a task; they're never launched into another task.

相反的，使用"singleTask "标记和"singleInstance "标记始终为根活动的活动。开启这样的活动会新建一个任务；而不是装入某个正在运行的任务。

• Whether there can be multiple instances of the activity . A "standard " or "singleTop " activity can be instantiated many times. They can belong to multiple tasks, and a given task can have multiple instances of the same activity.

是否允许产生多个活动实例。 2一个"standard" 或"singleTop "活动可以被多次实例化。他们可以属于多个任务，同样的活动可以在一个确定的任务中有多个实例。

In contrast, "singleTask " and "singleInstance " activities are limited to just one instance. Since these activities are at the root of a task, this limitation means that there is never more than a single instance of the task on the device at one time.

相反的，"singleTask 和"singleInstance "的活动只能有一个实例。因为这些活动是任务的根活动，这种限制意味着一个任务在同一时间只能有一个。
• Whether the instance can have other activities in its task . A "singleInstance " activity stands alone as the only activity in its task. If it starts another activity, that activity will be launched into a different task regardless of its launch mode — as if FLAG_ACTIVITY_NEW_TASK  was in the intent. In all other respects, the "singleInstance " mode is identical to "singleTask ".

所在任务中是否允许有其他活动。 "singleInstance "活动单独运行在一个任务中。如果他开启另一个活动，新一个活动不论启动模式都会运行在新任务中——就好像用带有FLAG_ACTIVITY_NEW_TASK 控制标的Intent对象激活似的。其他方面"singleInstance "与"singleTask "相同。

The other three modes permit multiple activities to belong to the task. A "singleTask " activity will always be the root activity of the task, but it can start other activities that will be assigned to its task. Instances of "standard " and "singleTop " activities can appear anywhere in a stack.

另外三个模式允许任务中存在多个活动。"singleTask "活动将总是任务的根活动，但是由他启动的其他活动会被装入他所在的任务。"standard "和"singleTop "活动能在任务栈中任何任何位置出现。

• Whether a new instance of the class will be launched to handle a new intent . For the default "standard " mode, a new instance is created to respond to every new intent. Each instance handles just one intent. For the "singleTop " mode, an existing instance of the class is re-used to handle a new intent if it resides at the top of the activity stack of the target task. If it does not reside at the top, it is not re-used. Instead, a new instance is created for the new intent and pushed on the stack.
获得新意图时是否使用新   类的   实例来操作。 对于默认"standard "的模式，每次获得新意图时都会用新的实例响应。每个实例响应一个意图。"singleTop "模式中，如果意图响应类实例存在且在   意图的目标任务   栈的栈顶，那么意图响应类实例将会被重用。如果存在但不再栈顶，则不会被重用。新实例被创建并压入栈顶。

For example, suppose a task's activity stack consists of root activity A with activities B, C, and D on top in that order, so the stack is A-B-C-D. An intent arrives for an activity of type D. If D has the default "standard " launch mode, a new instance of the class is launched and the stack becomes A-B-C-D-D. However, if D's launch mode is "singleTop ", the existing instance is expected to handle the new intent (since it's at the top of the stack) and the stack remains A-B-C-D.

例如，假设 一个任务的几个活动是   根活动A，活动B，C，D   的顺序，栈内就是A-B-C-D。这时收到一个类D进行响应的意图。如果D是"standard "启动模式，则将创建类的新实例，栈内变成A-B-C-D-D。但是如果D是"singleTop "启动模式，用以响应新意图的实例已经存在（而且已经在栈顶），栈保持A-B-C-D不变。

If, on the other hand, the arriving intent is for an activity of type B, a new instance of B would be launched no matter whether B's mode is "standard " or "singleTop " (since B is not at the top of the stack), so the resulting stack would be A-B-C-D-B.

如果，另一种情况，收到一个类B响应的意图，不管B的启动类型是"standard "还是"singleTop "（因为B不在栈顶），新实例都会被创建，之后的栈会变成A-B-C-D-B。

As noted above, there's never more than one instance of a "singleTask " or "singleInstance " activity, so that instance is expected to handle all new intents. A "singleInstance " activity is always at the top of the stack (since it is the only activity in the task), so it is always in position to handle the intent. However, a "singleTask " activity may or may not have other activities above it in the stack. If it does, it is not in position to handle the intent, and the intent is dropped. (Even though the intent is dropped, its arrival would have caused the task to come to the foreground, where it would remain.)

就像前面已经提到过的，"singleTask "和"singleInstance "活动的类永远不可能会出现多个实例。所以他们的类就会处理所有的收到的意图。"singleInstance "活动永远是任务的栈的最顶活动（因为他是任务中的唯一活动），因此他也总可以处理一个意图。但是在"singleTask "活动栈位之上可能也可能没有另外的活动。如果有，那么他就不能对新到的意图进行处理，这个意图就丢失了。（即使意图已经丢失，意图的收到也会出发任务使其被送到并保持在前台。）

When an existing activity is asked to handle a new intent, the Intent object is passed to the activity in an onNewIntent()   call. (The intent object that originally started the activity can be retrieved by calling getIntent()  .)

Note that when a new instance of an Activity is created to handle a new intent, the user can always press the BACK key to return to the previous state (to the previous activity). But when an existing instance of an Activity handles a new intent, the user cannot press the BACK key to return to what that instance was doing before the new intent arrived.

For more on launch modes, see the description of the <activity>   element.

### Clearing the stack——清理栈

If the user leaves a task for a long time, the system clears the task of all activities except the root activity. When the user returns to the task again, it's as the user left it, except that only the initial activity is present. The idea is that, after a time, users will likely have abandoned what they were doing before and are returning to the task to begin something new.

That's the default. There are some activity attributes that can be used to control this behavior and modify it:

The alwaysRetainTaskState   attribute——alwaysRetainTaskState  属性
If this attribute is set to "true " in the root activity of a task, the default behavior just described does not happen. The task retains all activities in its stack even after a long period.

The clearTaskOnLaunch   attribute——clearTaskOnLaunch  属性
If this attribute is set to "true " in the root activity of a task, the stack is cleared down to the root activity whenever the user leaves the task and returns to it. In other words, it's the polar opposite of alwaysRetainTaskState . The user always returns to the task in its initial state, even after a momentary absence.

The finishOnTaskLaunch   attribute——finishOnTaskLaunch  属性
This attribute is like clearTaskOnLaunch , but it operates on a single activity, not an entire task. And it can cause any activity to go away, including the root activity. When it's set to "true ", the activity remains part of the task only for the current session. If the user leaves and then returns to the task, it no longer is present.

There's another way to force activities to be removed from the stack. If an Intent object includes the FLAG_ACTIVITY_CLEAR_TOP   flag, and the target task already has an instance of the type of activity that should handle the intent in its stack, all activities above that instance are cleared away so that it stands at the top of the stack and can respond to the intent. If the launch mode of the designated activity is "standard ", it too will be removed from the stack, and a new instance will be launched to handle the incoming intent. That's because a new instance is always created for a new intent when the launch mode is "standard ".

FLAG_ACTIVITY_CLEAR_TOP  is most often used in conjunction with FLAG_ACTIVITY_NEW_TASK . When used together, these flags are a way of locating an existing activity in another task and putting it in a position where it can respond to the intent.

FLAG_ACTIVITY_CLEAR_TOP 通常会和FLAG_ACTIVITY_NEW_TASK 联合使用。一起使用时，这个组合是   找到另一个任务中的已有活动然后将它转入新的任务中以响应一个意图的   一种方法。

An activity is set up as the entry point for a task by giving it an intent filter with "android.intent.action.MAIN " as the specified action and "android.intent.category.LAUNCHER " as the specified category. (There's an example of this type of filter in the earlier Intent Filters  section.) A filter of this kind causes an icon and label for the activity to be displayed in the application launcher, giving users a way both to launch the task and to return to it at any time after it has been launched.

This second ability is important: Users must be able to leave a task and then come back to it later. For this reason, the two launch modes that mark activities as always initiating a task, "singleTask " and "singleInstance ", should be used only when the activity has a MAIN  and LAUNCHER  filter. Imagine, for example, what could happen if the filter is missing: An intent launches a "singleTask " activity, initiating a new task, and the user spends some time working in that task. The user then presses the HOME key. The task is now ordered behind and obscured by the home screen. And, because it is not represented in the application launcher, the user has no way to return to it.

A similar difficulty attends the FLAG_ACTIVITY_NEW_TASK  flag. If this flag causes an activity to begin a new task and the user presses the HOME key to leave it, there must be some way for the user to navigate back to it again. Some entities (such as the notification manager) always start activities in an external task, never as part of their own, so they always put FLAG_ACTIVITY_NEW_TASK  in the intents they pass to startActivity() . If you have an activity that can be invoked by an external entity that might use this flag, take care that the user has a independent way to get back to the task that's started.

For those cases where you don't want the user to be able to return to an activity, set the <activity>  element's finishOnTaskLaunch  to "true ". See Clearing the stack , earlier.

When the first of an application's components needs to be run, Android starts a Linux process for it with a single thread of execution. By default, all components of the application run in that process and thread.

However, you can arrange for components to run in other processes, and you can spawn additional threads for any process.

### Processes——进程

The process where a component runs is controlled by the manifest file. The component elements — <activity><service><receiver> , and <provider>  — each have a process  attribute that can specify a process where that component should run. These attributes can be set so that each component runs in its own process, or so that some components share a process while others do not. They can also be set so that components of different applications run in the same process — provided that the applications share the same Linux user ID and are signed by the same authorities. The <application>  element also has a process  attribute, for setting a default value that applies to all components.

All components are instantiated in the main thread of the specified process, and system calls to the component are dispatched from that thread. Separate threads are not created for each instance. Consequently, methods that respond to those calls — methods like View.onKeyDown()   that report user actions and the lifecycle notifications discussed later in the Component Lifecycles  section — always run in the main thread of the process. This means that no component should perform long or blocking operations (such as networking operations or computation loops) when called by the system, since this will block any other components also in the process. You can spawn separate threads for long operations, as discussed under Threads , next.

Android may decide to shut down a process at some point, when memory is low and required by other processes that are more immediately serving the user. Application components running in the process are consequently destroyed. A process is restarted for those components when there's again work for them to do.

Android系统可能会在某些时候结束一个进程，当内存不足且被其他对用户来说更紧要的进程请求时。因此，在此进程中的Android组件会被销毁。当这些组件有新的事要做时，系统会为他们重启进程。

When deciding which processes to terminate, Android weighs their relative importance to the user. For example, it more readily shuts down a process with activities that are no longer visible on screen than a process with visible activities. The decision whether to terminate a process, therefore, depends on the state of the components running in that process. Those states are the subject of a later section, Component Lifecycles .

Android权衡对用户的重要性关系来决定结束哪个进程。例如，一个不是正在显示的进程比正在显示的进程更容易被结束。是否要结束某个进程是由里边运行的组件的状态决定的。组建的状态是下边Component Lifecycles 章节的主题。

Even though you may confine your application to a single process, there will likely be times when you will need to spawn a thread to do some background work. Since the user interface must always be quick to respond to user actions, the thread that hosts an activity should not also host time-consuming operations like network downloads. Anything that may not be completed quickly should be assigned to a different thread.

Threads are created in code using standard Java Thread   objects. Android provides a number of convenience classes for managing threads — Looper   for running a message loop within a thread, Handler   for processing messages, andHandlerThread   for setting up a thread with a message loop.

### Remote procedure calls——远程过程调用

Android has a lightweight mechanism for remote procedure calls (RPCs) — where a method is called locally, but executed remotely (in another process), with any result returned back to the caller. This entails decomposing the method call and all its attendant data to a level the operating system can understand, transmitting it from the local process and address space to the remote process and address space, and reassembling and reenacting the call there. Return values have to be transmitted in the opposite direction. Android provides all the code to do that work, so that you can concentrate on defining and implementing the RPC interface itself.

Android 有一个轻量级的远程过程调用的机制（RPCs）——使得方法在本地调用，然后远程执行（在另一个进程中），并将所有结果返回本地。这需要将方法的调用和随 之的数据解释成操作系统可以识别的级别，将其从本地进程和地址空间传送到远程端的进程和地址空间中，在远程端重新装配和组织。返回数据传递过程相反。 Android提供了所有完成这些过程的代码，所以您可以将精力集中在RPC接口的定义和实现上。

An RPC interface can include only methods. All methods are executed synchronously (the local method blocks until the remote method finishes), even if there is no return value.

RPC接口可以只包含方法。所有的方法都是同步执行的（本地方法会等待远程方法），在没有返回值的情况下也是这样。

In brief, the mechanism works as follows: You'd begin by declaring the RPC interface you want to implement using a simple IDL (interface definition language). From that declaration, the aidl   tool generates a Java interface definition that must be made available to both the local and the remote process. It contains two inner class, as shown in the following diagram:

The inner classes have all the code needed to administer remote procedure calls for the interface you declared with the IDL. Both inner classes implement the IBinder   interface. One of them is used locally and internally by the system; the code you write can ignore it. The other, called Stub, extends the Binder   class. In addition to internal code for effectuating the IPC calls, it contains declarations for the methods in the RPC interface you declared. You would subclass Stub to implement those methods, as indicated in the diagram.

内部类中含有所有   用以管理您使用IDL声明的接口的远程过程调用   的代码。两个内部类都实现了IBinder 接口。一个被系统本地地，内部地使用；您自己写的代码会忽略掉它们。另一个，叫做Stub，由Binder  类派生。不仅含有执行IPC调用的代码，还含有您声明的RPC接口中方法的声明。就像图标中显示的，您应该继承Stub类来实现这些方法。

Typically, the remote process would be managed by a service (because a service can inform the system about the process and its connections to other processes). It would have both the interface file generated by the aidl  tool and the Stub subclass implementing the RPC methods. Clients of the service would have only the interface file generated by the aidl  tool.

Here's how a connection between a service and its clients is set up:

• Clients of the service (on the local side) would implement onServiceConnected()   and onServiceDisconnected()   methods so they can be notified when a successful connection to the remote service is established, and when it goes away. They would then call bindService()   to set up the connection.          服务器的客户端（即本地端）会实现 onServiceConnected() onServiceDisconnected() 方法，然后客户端在在远程服务连接建立或丢失时得知这一信息。然后客户端会调用bindService()  来对连接进行设定。
• The service's onBind()   method would be implemented to either accept or reject the connection, depending on the intent it receives (the intent passed to bindService() ). If the connection is accepted, it returns an instance of the Stub subclass.          根据接收的意图（意图被传递到bindService() ）服务的 onBind() 方法会被实现于接受或拒绝连接。如果连接被接受，方法返回一个Stub子类的实例。
• If the service accepts the connection, Android calls the client's onServiceConnected()  method and passes it an IBinder object, a proxy for the Stub subclass managed by the service. Through the proxy, the client can make calls on the remote service.          如果服务接受了连接，Android调用客户端的onServiceConnected() 方法并且传递给它一个IBinder对象，IBinder对象是由服务管理的Stub类的一个代理。通过这个代理，客户端可以调用远程端上的服务。

This brief description omits some details of the RPC mechanism. For more information, see Designing a Remote Interface Using AIDL  and the IBinder   class description.这个简要的RPC机制介绍省略了一些细节。更多信息请看Interface Using AIDLIBinder  类的介绍。

In a few contexts, the methods you implement may be called from more than one thread, and therefore must be written to be thread-safe.

This is primarily true for methods that can be called remotely — as in the RPC mechanism discussed in the previous section. When a call on a method implemented in an IBinder object originates in the same process as the IBinder, the method is executed in the caller's thread. However, when the call originates in another process, the method is executed in a thread chosen from a pool of threads that Android maintains in the same process as the IBinder; it's not executed in the main thread of the process. For example, whereas a service's onBind()  method would be called from the main thread of the service's process, methods implemented in the object that onBind()  returns (for example, a Stub subclass that implements RPC methods) would be called from threads in the pool. Since services can have more than one client, more than one pool thread can engage the same IBinder method at the same time. IBinder methods must, therefore, be implemented to be thread-safe.

Similarly, a content provider can receive data requests that originate in other processes. Although the ContentResolver and ContentProvider classes hide the details of how the interprocess communication is managed, ContentProvider methods that respond to those requests — the methods query() insert() delete() update()  , and getType()   — are called from a pool of threads in the content provider's process, not the main thread of the process. Since these methods may be called from any number of threads at the same time, they too must be implemented to be thread-safe.

## Component Lifecycles——组件生命周期

Application components have a lifecycle — a beginning when Android instantiates them to respond to intents through to an end when the instances are destroyed. In between, they may sometimes be active or inactive,or, in the case of activities, visible to the user or invisible. This section discusses the lifecycles of activities, services, and broadcast receivers — including the states that they can be in during their lifetimes, the methods that notify you of transitions between states, and the effect of those states on the possibility that the process hosting them might be terminated and the instances destroyed.

### Activity lifecycle——活动的生命周期

An activity has essentially three states:

• It is active  or running  when it is in the foreground of the screen (at the top of the activity stack for the current task). This is the activity that is the focus for the user's actions.          当他在前台时（在当前任务的活动栈的栈顶）是activerunning 的（活动的或运行中的）。这种活动是正在关注用户动作的。
• It is paused  if it has lost focus but is still visible to the user. That is, another activity lies on top of it and that activity either is transparent or doesn't cover the full screen, so some of the paused activity can show through. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.          失去用户关注，但是仍然是可见的   是paused （暂停）状态。就是说，另一个透明或不覆盖整个屏幕的活动覆盖在了这个活动之上，因此部分paused 的活动的界面还是显示出来的。暂停的活动依然是存活的（他保持着所有的状态和成员信息并且保持着和窗口管理器的联系），但是会在系统运行内存极低的情况下被关闭。

• It is stopped  if it is completely obscured by another activity. It still retains all state and member information. However, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.          当一个活动被另一个活动完全覆盖时，就是stopped （停止）状态。停止的活动保留着所有的状态和成员信息。但是，因为他已经处于不可见状态，他的窗口就被隐藏了，而且通常系统会在内存需要用在别的地方时关闭停止的活动。

If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling its finish()   method), or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.

As an activity transitions from state to state, it is notified of the change by calls to the following protected methods:

void onCreate(Bundle savedInstanceState )
void onStart()
void onRestart()
void onResume()
void onPause()
void onStop()
void onDestroy()

All of these methods are hooks that you can override to do appropriate work when the state changes. All activities must implement onCreate()   to do the initial setup when the object is first instantiated. Many will also implement onPause()  to commit data changes and otherwise prepare to stop interacting with the user.

Taken together, these seven methods define the entire lifecycle of an activity. There are three nested loops that you can monitor by implementing them:

• call to onCreate()   through to a single final call to onDestroy()  . An activity does all its initial setup of "global" state in onCreate() , and releases all remaining resources inonDestroy() . For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate()  and then stop the thread inonDestroy() .         从调用 onCreate() 一直到结束性的 onDestroy() 的调用。活动在onCreate() 中进行所有“全局”状态的初始化，后释放所有占用的资源例如，如果一个活动有一个后台的从网络上下载数据的线程，活动可能会使用onCreate() 创建线程，使用onDestroy() 停止线程。
• The visible lifetime  of an activity happens between a call to onStart()   until a corresponding call to onStop()  . During this time, the user can see the activity on-screen, though it may not be in the foreground and interacting with the user. Between these two methods, you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver   in onStart()  to monitor for changes that impact your UI, and unregister it in onStop()  when the user can no longer see what you are displaying. The onStart()  and onStop()  methods can be called multiple times, as the activity alternates between being visible and hidden to the user.          活动可见的时间是 onStart() 的调用到相应的 onStop() 的调用之间的时间。这段时间用户可以在屏幕上看到这个活动，即便这个活动可能不在前台，没在和用户进行交互。在这两个方法的调用之间的时间，您可以保持将活动展现给用户的资源。例如，您可以在onStart() 中注册一个BroadcastReceiver 来监控UI的变化，然后在用户不能再看到您要显示的后在onStop() 中注销它。活动在可见和隐藏间切换过程中，onStart()onStop() 会被调用多次。

• The foreground lifetime  of an activity happens between a call to onResume()   until a corresponding call to onPause()  . During this time, the activity is in front of all other activities on screen and is interacting with the user. An activity can frequently transition between the resumed and paused states — for example, onPause()  is called when the device goes to sleep or when a new activity is started, onResume()  is called when an activity result or a new intent is delivered. Therefore, the code in these two methods should be fairly lightweight.          活动的前台时间是onResume()  和对应的 onPause() 的调用之间的时间。这段时间中，活动处在其他活动之上，并和用户进行交互。活动可以在暂停和继续之间多次切换——例如，当设备休眠或启动了新的活动，onPause() 会被调用，收到新启动活动返回结果或旧活动收到新意图时，onResume() 会被调用。所以这两个方法中的代码应绝对轻量。

The following diagram illustrates these loops and the paths an activity may take between states. The colored ovals are major states the activity can be in. The square rectangles represent the callback methods you can implement to perform operations when the activity transitions between states.

The following table describes each of these methods in more detail and locates it within the activity's overall lifecycle:

Method——方法 Description——详情 Killable?——是否可结束？ Next——下一步
onCreate()  Called when the activity is first created. This is where you should do all of your normal static set up — create views, bind data to lists, and so on. This method is passed a Bundle object containing the activity's previous state, if that state was captured (see Saving Activity State , later).

Always followed by onStart() .

No

onStart()
onRestart()  Called after the activity has been stopped, just prior to it being started again.

Always followed by onStart()  下一步总是onStart()

No

onStart()
onStart()  Called just before the activity becomes visible to the user.

Followed by onResume()  if the activity comes to the foreground, or onStop()  if it becomes hidden.

No

onResume()
or
onStop()  onResume() 或是onStop()
onResume()  Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack, with user input going to it.

Always followed by onPause() .

No

onPause()
onPause()  Called when the system is about to start resuming another activity. This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on. It should do whatever it does very quickly, because the next activity will not be resumed until it returns.

Followed either by onResume()  if the activity returns back to the front, or by onStop()  if it becomes invisible to the user.

Yes

onResume()
or
onStop()
onStop()  Called when the activity is no longer visible to the user. This may happen because it is being destroyed, or because another activity (either an existing one or a new one) has been resumed and is covering it.

Followed either by onRestart()  if the activity is coming back to interact with the user, or by onDestroy()  if this activity is going away.

Yes

onRestart()
or
onDestroy()
onDestroy()  Called before the activity is destroyed. This is the final call that the activity will receive. It could be called either because the activity is finishing (someone called finish()   on it), or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing()   method.

Yes

nothing

Note the Killable  column in the table above. It indicates whether or not the system can kill the process hosting the activity at any time after the method returns, without executing another line of the activity's code . Three methods (onPause()onStop() , and onDestroy() ) are marked "Yes." Because onPause()  is the first of the three, it's the only one that's guaranteed to be called before the process is killed — onStop()  and onDestroy()  may not be. Therefore, you should use onPause()  to write any persistent data (such as user edits) to storage.

Methods that are marked "No" in the Killable  column protect the process hosting the activity from being killed from the moment they are called. Thus an activity is in a killable state, for example, from the time onPause()  returns to the timeonResume()  is called. It will not again be killable until onPause()  again returns.
Ki llable？——是否可结束？ 一栏标注着“No”的方法保护了其所在进程在这个方法调用之时起不被结束。就是说，例如在onPause() 方法完成之后到onResume() 被调用之前这段时间之内，进程是可能被结束的。然后到下一次onPause() 完成之前，进程是不可结束的。

As noted in a later section, Processes and lifecycle , an activity that's not technically "killable" by this definition might still be killed by the system — but that would happen only in extreme and dire circumstances when there is no other recourse.

#### Saving activity state——保存活动状态

When the system, rather than the user, shuts down an activity to conserve memory, the user may expect to return to the activity and find it in its previous state.

To capture that state before the activity is killed, you can implement an onSaveInstanceState()   method for the activity. Android calls this method before making the activity vulnerable to being destroyed — that is, before onPause()  is called. It passes the method a Bundle   object where you can record the dynamic state of the activity as name-value pairs. When the activity is again started, the Bundle is passed both to onCreate()  and to a method that's called afteronStart()onRestoreInstanceState()  , so that either or both of them can recreate the captured state.

Unlike onPause()  and the other methods discussed earlier, onSaveInstanceState()  and onRestoreInstanceState()  are not lifecycle methods. They are not always called. For example, Android calls onSaveInstanceState()  before the activity becomes vulnerable to being destroyed by the system, but does not bother calling it when the instance is actually being destroyed by a user action (such as pressing the BACK key). In that case, the user won't expect to return to the activity, so there's no reason to save its state.

Because onSaveInstanceState()  is not always called, you should use it only to record the transient state of the activity, not to store persistent data. Use onPause()  for that purpose instead.

#### Coordinating activities——协调活动

When one activity starts another, they both experience lifecycle transitions. One pauses and may stop, while the other starts up. On occasion, you may need to coordinate these activities, one with the other.

The order of lifecycle callbacks is well defined, particularly when the two activities are in the same process:

1. The current activity's onPause()  method is called.——当前的活动的onPause() 方法被调用·。
2. Next, the starting activity's onCreate()onStart() , and onResume()  methods are called in sequence.——然后，新一个活动的onCreate()onStart()onResume() 方法依次被调用。
3. Then, if the starting activity is no longer visible on screen, its onStop()  method is called.——然后，如果旧一个活动在屏幕上不再可见，他的onStop() 方法会被调用。

### Service lifecycle——服务的生命周期

A service can be used in two ways:

• It can be started and allowed to run until someone stops it or it stops itself. In this mode, it's started by calling Context.startService()   and stopped by calling Context.stopService()  . It can stop itself by callingService.stopSelf()   or Service.stopSelfResult()  . Only one stopService()  call is needed to stop the service, no matter how many times startService()  was called.——他可以启动并运行指导什么将它停止或她自己停止。在这种模式中，他通过调用Context.startService()  开启，通过调用Context.stopService()  停止。服务能通过调用Service.stopSelf() Service.stopSelfResult()  停止自己。停止一个服务只需一个stopService() 的调用，不管用了多少次startService()
• It can be operated programmatically using an interface that it defines and exports. Clients establish a connection to the Service object and use that connection to call into the service. The connection is established by callingContext.bindService()  , and is closed by calling Context.unbindService()  . Multiple clients can bind to the same service. If the service has not already been launched, bindService()  can optionally launch it. ——对服务可以使用他定义和导出的接口进行  编程性的操作。客户端建立一个到Service对象的连接，然后使用这个连接对服务进行请求。连接使用Context.bindService()  建立，使用Context.unbindService()  断开。多个客户端可以绑定到一个服务。如果服务还未被启动，可用bindService() 启动它。

The two modes are not entirely separate. You can bind to a service that was started with startService() . For example, a background music service could be started by calling startService()  with an Intent object that identifies the music to play. Only later, possibly when the user wants to exercise some control over the player or get information about the current song, would an activity establish a connection to the service by calling bindService() . In cases like this,stopService()  will not actually stop the service until the last binding is closed.

Like an activity, a service has lifecycle methods that you can implement to monitor changes in its state. But they are fewer than the activity methods — only three — and they are public, not protected:

void onCreate()
void onStart(Intent intent )
void onDestroy()

By implementing these methods, you can monitor two nested loops of the service's lifecycle:

• The entire lifetime  of a service happens between the time onCreate()   is called and the time onDestroy()   returns. Like an activity, a service does its initial setup in onCreate() , and releases all remaining resources in onDestroy() . For example, a music playback service could create the thread where the music will be played in onCreate() , and then stop the thread in onDestroy() .——服务的整个存在时间是从onCreate()  被调用到onDestroy()  完成。像活动一样，服务在onCreate() 被调用时进行初始化设置，在onDestroy() 中完成占有的资源的释放。例如，音乐播放服务会在onCreate() 中为音乐的播放建立新的线程，然后在onDestroy() 中结束线程。
• The active lifetime  of a service begins with a call to onStart()  . This method is handed the Intent object that was passed to startService() . The music service would open the Intent to discover which music to play, and begin the playback.——服务的动作时间是从onStart()  的调用开始的。传递给startService() 的Intent对象又被传递给这个方法。音乐播放服务会打开这个意图找到要播放哪个歌曲，然后开始播放。

There's no equivalent callback for when the service stops — no onStop()  method.

服务没有像活动的停止时的回调方法——就是没有onStop() 方法。

The onCreate()  and onDestroy()  methods are called for all services, whether they're started by Context.startService()   or Context.bindService()  . However, onStart()  is called only for services started by startService() .

If a service permits others to bind to it, there are additional callback methods for it to implement:

IBinder onBind(Intent intent )
boolean onUnbind(Intent intent )
void onRebind(Intent intent )

The onBind()   callback is passed the Intent object that was passed to bindService  and onUnbind()   is handed the intent that was passed to unbindService() . If the service permits the binding, onBind()  returns the communications channel that clients use to interact with the service. The onUnbind()  method can ask for onRebind()   to be called if a new client connects to the service.

onBind()  方法获得传递给bindService 的Intent对象，onUnbind()  方法获得传递unbindService() 给的Intent对象如果服务允许绑定，onBind() 返回客户端用以和服务交互的信道。onUnbind() 方法可以在新的客户连接到服务时让系统调用onRebind() 

The following diagram illustrates the callback methods for a service. Although, it separates services that are created via startService  from those created by bindService() , keep in mind that any service, no matter how it's started, can potentially allow clients to bind to it, so any service may receive onBind()  and onUnbind()  calls.

void onReceive(Context curContext , Intent broadcastMsg )

When a broadcast message arrives for the receiver, Android calls its onReceive()   method and passes it the Intent object containing the message. The broadcast receiver is considered to be active only while it is executing this method. When onReceive()  returns, it is inactive.

A process with an active broadcast receiver is protected from being killed. But a process with only inactive components can be killed by the system at any time, when the memory it consumes is needed by other processes.

This presents a problem when the response to a broadcast message is time consuming and, therefore, something that should be done in a separate thread, away from the main thread where other components of the user interface run. IfonReceive()  spawns the thread and then returns, the entire process, including the new thread, is judged to be inactive (unless other application components are active in the process), putting it in jeopardy of being killed. The solution to this problem is for onReceive()  to start a service and let the service do the job, so the system knows that there is still active work being done in the process.

The next section has more on the vulnerability of processes to being killed.

### Processes and lifecycles——进程和生命周期

The Android system tries to maintain an application process for as long as possible, but eventually it will need to remove old processes when memory runs low. To determine which processes to keep and which to kill, Android places each process into an "importance hierarchy" based on the components running in it and the state of those components. Processes with the lowest importance are eliminated first, then those with the next lowest, and so on. There are five levels in the hierarchy. The following list presents them in order of importance:
Android 系统试图将应用程序的进程保持最长的时间，但是最终当内存不足时，还是需要将不用的进程结束掉。为了判断哪些进程该结束，哪些不该， Android将每个进程按照当中运行的组件和组件的状态  排放到一个“重要程度排行表”中。最不重要的最先结束，然后是次不重要的，依此类推。“重要程度排行表”中有五层重要程度。下面的表按重要程度顺序列出了 他们：

1. foreground process  is one that is required for what the user is currently doing. A process is considered to be in the foreground if any of the following conditions hold:——前台进程是需要获取用户正在做得事情的进程。进程有下列情况的，即认定为前台进程：
• It is running an activity that the user is interacting with (the Activity object's onResume()   method has been called).——正在运行一个用户正与之交互的活动（即活动的 onResume() 方法被调用了）
• It hosts a service that's bound to the activity that the user is interacting with.——承载了一个   用户正在与之交互的活动所属的   服务。

• It has a Service   object that's executing one of its lifecycle callbacks (onCreate() onStart()  , or onDestroy()  ).——承载着一个正在执行其生命周期回调方法（ onCreate() onStart() onDestroy() ）的Service 对象。

• It has a BroadcastReceiver   object that's executing its onReceive()   method.——承载了一个正在运行其 onReceive() 方法的BroadcastReceiver  对象。

Only a few foreground processes will exist at any given time. They are killed only as a last resort — if memory is so low that they cannot all continue to run. Generally, at that point, the device has reached a memory paging state, so killing some foreground processes is required to keep the user interface responsive.——任一时刻只会有很少的前台进程存在。结束他们是没有办法的办法——只有当内存不足到他们都没法运行了。通常情况下，到了这种状 况，设备就到了内存分页状态，结束一些前台进程是为了保持用户界面的响应。

2. visible process  is one that doesn't have any foreground components, but still can affect what the user sees on screen. A process is considered to be visible if either of the following conditions holds:——可见进程是没有任何前台组件，但是依旧可以被用户看见的进程。进程有下列情况之一的，即认定为前台进程：

• It hosts an activity that is not in the foreground, but is still visible to the user (its onPause()   method has been called). This may occur, for example, if the foreground activity is a dialog that allows the previous activity to be seen behind it.——承载着不在前台的活动，但是活动依旧能被用户看到（活动的 onPause() 方法被调用了）。例如当前台活动是一个没有完全盖住旧一个活动对话框时这种情况就可能发生。
• It hosts a service that's bound to a visible activity.——承载了一个属于可见活动的服务。

A visible process is considered extremely important and will not be killed unless doing so is required to keep all foreground processes running.——可见进程也是极为重要的，除非结束可见进程是为了保持前台进程的运行，否则可见进程是不会被结束的。

3. service process  is one that is running a service that has been started with the startService()   method and that does not fall into either of the two higher categories. Although service processes are not directly tied to anything the user sees, they are generally doing things that the user cares about (such as playing an mp3 in the background or downloading data on the network), so the system keeps them running unless there's not enough memory to retain them along with all foreground and visible processes.——服务进程是   运行着一个由 startService() 方法启动的并且不在前两种所述情况中的服务的   进程。虽然服务进程不与任何用户可见部分直接相连，但他们通常是在做一些用户关心的事（例如在后台播放音乐或从网上下载数据），所以除非内存不足以盛放前台和可见进程，系统是不会结束服务进程的。

4. background process  is one holding an activity that's not currently visible to the user (the Activity object's onStop()   method has been called). These processes have no direct impact on the user experience, and can be killed at any time to reclaim memory for a foreground, visible, or service process. Usually there are many background processes running, so they are kept in an LRU (least recently used) list to ensure that the process with the activity that was most recently seen by the user is the last to be killed. If an activity implements its lifecycle methods correctly, and captures its current state, killing its process will not have a deleterious effect on the user experience.——后台进程是承载目前用户不可见的活动（Activity的 onStop() 方 法被调用后）的进程。后台进程不直接影响用户体验，而且随时可以结束以回收供前台进程、可见进程和服务进程使用。通常同一时间会有很多正在运行的后台进 程，因此他们被存放在LRU（最近使用过的）列表中以保证最后含有用户最后使用的活动的进程是最后被结束的。如果活动正确地实现了其生命周期方法截获了当 前状态，那么结束他所在进程不会对用户体验有坏的影响。

5. An empty process  is one that doesn't hold any active application components. The only reason to keep such a process around is as a cache to improve startup time the next time a component needs to run in it. The system often kills these processes in order to balance overall system resources between process caches and the underlying kernel caches.——空进程是不包含任何活动的进程。保留空进程的唯一原因是作为缓存以提升组件下次使需要用他的开始速度。系统经常会结束这样的进程以平衡    在进程缓存和底层内核缓存之间的   整体系统资源。

Android ranks a process at the highest level it can, based upon the importance of the components currently active in the process. For example, if a process hosts a service and a visible activity, the process will be ranked as a visible process, not a service process.
Android依据在进程中正在活动的组件的重要程度   将进程排在他能处在的最高级。例如，如果一个进程承载了一个服务和一个可见进程，那么此进程就被排为可见进程，而不是服务进程。

In addition, a process's ranking may be increased because other processes are dependent on it. A process that is serving another process can never be ranked lower than the process it is serving. For example, if a content provider in process A is serving a client in process B, or if a service in process A is bound to a component in process B, process A will always be considered at least as important as process B.

Because a process running a service is ranked higher than one with background activities, an activity that initiates a long-running operation might do well to start a service for that operation, rather than simply spawn a thread — particularly if the operation will likely outlast the activity. Examples of this are playing music in the background and uploading a picture taken by the camera to a web site. Using a service guarantees that the operation will have at least "service process" priority, regardless of what happens to the activity. As noted in the Broadcast receiver lifecycle  section earlier, this is the same reason that broadcast receivers should employ services rather than simply put time-consuming operations in a thread.

• 本文已收录于以下专栏：

举报原因： 您举报文章：pplication Fundamentals——应用程序基础知识 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)