activity详解(一 官方注释篇)
一,官方注释与翻译
An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with {@link #setContentView}. While activities are often presented to the user as full-screen windows, they can also be used in other ways: as floating windows (via a theme with {@link android.R.attr#windowIsFloating} set) or embedded inside of another activity (using {@link ActivityGroup}). There are two methods almost all subclasses of Activity will implement:
一个Activity是一个用户可以触摸使用的最简单的一个单位,几乎所有的activity们都和用户交互,所以Activity类会在setContentView方法内放置一个UI布局以创建一个窗口,虽然Activity们一般以全屏显示的方式呈现给用户,它们也可以有其他的用法,比方说作为悬浮窗,或者被内嵌在其他的activity中,以下是几乎所有的Activity子类都会实现的两个方法
- {@link #onCreate} is where you initialize your activity. Most importantly, here you will usually call {@link #setContentView(int)} with a layout resource defining your UI, and using {@link #findViewById} to retrieve the widgets in that UI that you need to interact with programmatically.
- onCreate方法在你初始化你的activity的时候执行,最重要的是,你几乎总是会使用setContentView方法,以一个layout资源文件来定义你的UI,然后使用findViewById来绑定你的UI控件以便和代码交互
- {@link #onPause} is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the {@link android.content.ContentProvider} holding the data).
- onPause方法用于处理用户离开你的activity时所需要的工作,最重要的是,用户所做的任何改动都应该被提交(一般使用ContentProvider以保存数据)
To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all activity classes must have a corresponding {@link android.R.styleable#AndroidManifestActivity <activity>} declaration in their package's AndroidManifest.xml
.
为了使activity能够被使用,所有的activity类都需要被对应地定义在它们对应包内的AndroidManifest.xml内
Activity Lifecycle
Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity -- the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.
系统中的Activity们被一个activity栈管理,当一个新的activity被启动,它将会被放置在栈顶成为正在运行的activity--之前的activity总是被保留在栈内,并且在这个新的activity退出前不会被前台显示
An activity has essentially four states:
一个activity本质上有四种状态
- If an activity is in the foreground of the screen (at the top of the stack), it is active or running.
- 如果一个activity在屏幕显示,即前台显示(位于栈顶),称之为active(活动)或者running(运行)
- If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. 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.
- 如果一个activity失去了焦点但它依然可见(也就是说,一个新的非全屏或者透明的activity在该activity之上,并且获取了焦点),称之为paused(暂停),一个暂停态的activity是完全存活的(它保持着所有状态和成员信息并且依然保持着和窗口管理器的连接),但是如果在剩余内存极低的情况下,它可能被系统杀死
- If an activity is completely obscured by another activity, it is stopped. 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.
- 如果一个activity被另一个activity完全遮盖,称之为stopped(停止).它依然保留着所有状态和成员信息,无论如何,它不再对用户可见,所以它的窗口是隐藏起来的,并且在其他地方需要占用内存的时候,他经常会被系统杀死
- If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.
- 如果一个activity是暂停或者停止态的,当有其他请求需要结束这个activity时,系统将会结束掉它,或者直接杀死它的进程,当它再次展现给用户的时候,它一定是被重新启动和恢复先前的状态的
The following diagram shows the important state paths of an Activity. The square rectangles represent callback methods you can implement to perform operations when the Activity moves between states. The colored ovals are major states the Activity can be in.
下图展示了Activity主要的状态。当Activity在不同状态之间变化时,你可以去实现这些正方形表示的回调方法来操作Activity,这些回调方法用长方形表示。上色了的椭圆则表示Activity的主要状态
There are three key loops you may be interested in monitoring within your activity:
在你的activity中你可能会有兴趣关注三个关键的循环
- The entire lifetime of an activity happens between the first call to {@link android.app.Activity#onCreate} through to a single final call to {@link android.app.Activity#onDestroy}. An activity will do all setup of "global" state in onCreate(), and release all remaining resources in onDestroy(). 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 in onDestroy().
- Activity的整个生命周期起始于第一次调用onCreate()方法,终于最后调用onDestroy()。一个Activity会在onCreate()方法中做所有关于“全局”状态的步骤,并且在onDestroy()释放所有剩余的资源。例如,如果有一个在后台运行的从网络上下载数据的线程,它可能在onCreate()创建,并于onDestroy()结束。
- The visible lifetime of an activity happens between a call to {@link android.app.Activity#onStart} until a corresponding call to {@link android.app.Activity#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 {@link android.content.BroadcastReceiver} in onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user no longer sees what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user.
- Activity的可见生命周期开始于onStart(),直到与其对应的onStop()的调用,在这期间用户可以在屏幕上看见这个activity,尽管它可能不在前台与用户交互。在这两个方法之间你可以一直持有你需要在activity上展示给用户的资源。举个例子,你可以在onStart()方法中注册一个BroadcastReceiver去监控你UI改变造成的一些影响,然后当用户看不到你所展示的东西的时候,可以在onStop()方法中注销它,在activity对用户显示和隐藏的不断切换中,onStart()和onStop()方法可以被多次调用
- The foreground lifetime of an activity happens between a call to {@link android.app.Activity#onResume} until a corresponding call to {@link android.app.Activity#onPause}. During this time the activity is in front of all other activities and interacting with the user. An activity can frequently go between the resumed and paused states -- for example when the device goes to sleep, when an activity result is delivered, when a new intent is delivered -- so the code in these methods should be fairly lightweight.
- Activity的前台生命周期开始于onResume()方法的调用,直到与其对应的onPause()方法的调用,在这期间activity位于其他activity的前面并与用户交互。一个activity可以频繁的在resumed和paused两种状态中切换--举个例子,当手机休眠时,当一个activity传递了一个结果时,当一个新的intent传递时 -- 所以这两个方法中的代码应该是非常轻量级的
The entire lifecycle of an activity is defined by the following Activity methods. All of these are hooks that you can override to do appropriate work when the activity changes state. All activities will implement {@link android.app.Activity#onCreate} to do their initial setup; many will also implement {@link android.app.Activity#onPause} to commit changes to data and otherwise prepare to stop interacting with the user. You should always call up to your superclass when implementing these methods.
Activity的整个生命周期被下面Activity的方法定义。当Activity改变状态时,所有这些方法都是你可以重写来做合适的任务的钩子方法。所有的Activity都会实现onCreate()方法来做它们的初始化安装;许多Activity也会实现onPause()来提交用户改变的数据和做其他准备停止和用户交互的工作。你应该总是调用超类方法,在重写实现这些方法时。
public class Activity extends ApplicationContext { protected void onCreate(Bundle savedInstanceState); protected void onStart(); protected void onRestart(); protected void onResume(); protected void onPause(); protected void onStop(); protected void onDestroy(); }
In general the movement through an activity's lifecycle looks like this:
一般来说Activity生命周期的移动看起来像这样:
Method | Description | Killable? | Next | ||
---|---|---|---|---|---|
{@link android.app.Activity#onCreate 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, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
Always followed by |
No | onStart() |
||
{@link android.app.Activity#onRestart onRestart()} | Called after your activity has been stopped, prior to it being started again.
Always followed by |
No | onStart() |
||
{@link android.app.Activity#onStart onStart()} | Called when the activity is becoming visible to the user.
Followed by |
No | onResume() or onStop() |
||
{@link android.app.Activity#onResume onResume()} | Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.
Always followed by |
No | onPause() |
||
{@link android.app.Activity#onPause onPause()} | Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.
Followed by either |
Pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} | onResume() oronStop() |
||
{@link android.app.Activity#onStop onStop()} | Called when the activity is no longer visible to the user, because
another activity has been resumed and is covering this one. This
may happen either because a new activity is being started, an existing
one is being brought in front of this one, or this one is being
destroyed.
Followed by either |
Yes | onRestart() oronDestroy() |
||
{@link android.app.Activity#onDestroy onDestroy()} | The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called {@link Activity#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 {@link Activity#isFinishing} method. | Yes | nothing |
Note the "Killable" column in the above table -- for those methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed. Because of this, you should use the {@link #onPause} method to write any persistent data (such as user edits) to storage. In addition, the method {@link #onSaveInstanceState(Bundle)} is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in {@link #onCreate} if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data in {@link #onPause} instead of {@link #onSaveInstanceState} because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.
关于上表中的“Killable”列 - 对于那些被标记为可杀死的方法,在那个方法返回之后,持有这个Activity的进程可能会被系统在任何时候杀死而不执行下面的代码。因此,你应该使用onPause()方法来写任何持久化数据来保存。另外,onSaveInstanceState(Bundle)方法会在Activity被放置到后台之前被调用,让你可以保存任何动态实例状态在Bundle,如果Activity重启的话点会在onCreate(Bundle)接收。查看Process Lifecycle章节可以看到更多关于联系到Activity的生命周期的信息。需要注意的是持久化应该在onPause()做而不是onSaveInstanceState(Bundle)因为后者不是生命周期的回调,并不是每次都会被调用。
Be aware that these semantics will change slightly between applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB} vs. those targeting prior platforms. Starting with Honeycomb, an application is not in the killable state until its {@link #onStop} has returned. This impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be safely called after {@link #onPause()} and allows and application to safely wait until {@link #onStop()} to save persistent state.
需要注意的是这些语法在应用的3.0平台之后和之前可能会稍微改变。
Android 3.0之后,onStop()返回之前应用是不可杀的。
onSaveInstanceState(Bundle)的调用可能会受影响(它会在onPause()
之后安全地调用并且允许应用在onStop()之前安全地等待,来保存持久化状
态)。
For those methods that are not marked as being killable, the activity's process will not be killed by the system starting from the time the method is called and continuing after it returns. Thus an activity is in the killable state, for example, between after onPause()
to the start of onResume()
.
对于那些没有被标记为killable的方法,方法在被调用直到返回之前,Activity的进程不会被系统干掉。因此Activity是处于killable状态,例如,onPause()之后onResume()之前。(不理解,延伸解读为:一个Activity开启另一个Activity时,前者会调用onPause但是在后者onResume之前,前者不会被系统干掉,因为处于不可杀时期;或者解读为:一个Activity被放置到后台只是调用了onPause下次切换回来时会调用onResume,在此期间,也是处于不可杀时期,不会被系统干掉。)
Configuration Changes
If the configuration of the device (as defined by the {@link Configuration Resources.Configuration} class) changes, then anything displaying a user interface will need to update to match that configuration. Because Activity is the primary mechanism for interacting with the user, it includes special support for handling configuration changes.
如果设备的配置改变(正如Resources.Configuration类定义),所有对用户展示的接口将需要更新到适配该配置。因为Activity是和用户交互的主要途径,它包括特别是支持来处理配置改变。
Unless you specify otherwise, a configuration change (such as a change in screen orientation, language, input devices, etc) will cause your current activity to be destroyed, going through the normal activity lifecycle process of {@link #onPause}, {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity had been in the foreground or visible to the user, once {@link #onDestroy} is called in that instance then a new instance of the activity will be created, with whatever savedInstanceState the previous instance had generated from {@link #onSaveInstanceState}.
除非你特别指定,否则,配置的改变(例如横竖屏,语言,输入法等等)将会导致当前Activity销毁,通过普通的Activity生命周期过程,onPause(),onStop(),和onDestroy()。如果Activity在前台或者对用户可见,一旦这个实例的onDestroy()被调用,新的实例的Activity会被创建,带着前一个实例在onSaveInstanceState(Bundle)里保存的东西。
This is done because any application resource, including layout files, can change based on any configuration value. Thus the only safe way to handle a configuration change is to re-retrieve all resources, including layouts, drawables, and strings. Because activities must already know how to save their state and re-create themselves from that state, this is a convenient way to have an activity restart itself with a new configuration.
这代表着结束因为任何应用资源,包括布局文件,都会随着配置值改变。因此仅有的处理配置改变的安全方式是重新检索所有资源,包括布局文件,图片资源,字符串。因为Activity必须知道如何保存它们的状态和自己通过状态重建自己,这是让Activity通过新配置自己重启的方便方式。
In some special cases, you may want to bypass restarting of your activity based on one or more types of configuration changes. This is done with the {@link android.R.attr#configChanges android:configChanges} attribute in its manifest. For any types of configuration changes you say that you handle there, you will receive a call to your current activity's {@link #onConfigurationChanged} method instead of being restarted. If a configuration change involves any that you do not handle, however, the activity will still be restarted and {@link #onConfigurationChanged} will not be called.
在一些特别的情况下,你可能需要忽略基于一个或多个类型配置改变带来的重启。通过manifest文件里的android:configChanges属性来处理就可以。对于任何配置改变,你会接收到当前Activity的onConfigurationChanged(Configuration)方法调用而不是重启。如果一个配置改变调用牵涉到任何你不处理的东西,Activity仍然会重启而不调用onConfigurationChanged(Configuration)。
Starting Activities and Getting Results
The {@link android.app.Activity#startActivity} method is used to start a new activity, which will be placed at the top of the activity stack. It takes a single argument, an {@link android.content.Intent Intent}, which describes the activity to be executed.
startActivity(Intent)方法用来打开一个新的Activity,放在Activity栈顶。它只使用单一变量,一个描述等待被执行的Activity的Intent。
Sometimes you want to get a result back from an activity when it ends. For example, you may start an activity that lets the user pick a person in a list of contacts; when it ends, it returns the person that was selected. To do this, you call the {@link android.app.Activity#startActivityForResult(Intent, int)} version with a second integer parameter identifying the call. The result will come back through your {@link android.app.Activity#onActivityResult} method.
有时候你想要从一个Activity的结束获得一个结果。例如,你可能打开一个Activity让用户从联系人列表里选一个人;当选择结束的时候,会返回被选择的人。为此,你可以调用startActivityForResult(Intent,int)第二个整数型参数辨识调用者。通过onActivityResult(int,int,Intent)方法会返回结果。
When an activity exits, it can call {@link android.app.Activity#setResult(int)} to return data back to its parent. It must always supply a result code, which can be the standard results RESULT_CANCELED, RESULT_OK, or any custom values starting at RESULT_FIRST_USER. In addition, it can optionally return back an Intent containing any additional data it wants. All of this information appears back on the parent's Activity.onActivityResult()
, along with the integer identifier it originally supplied.
当一个Activity退出时,它会调用setResult(int)来返回数据给父亲。它总是必须提供一个结果码,可以是标准的结果 RESULT_CANCELED,RESULT_OK,或者任何从RESULT_FIRST_USER 开始的自定义的值。另外,可以有选择地返回一个Intent,用来含括任何额外的数据。所有的这些信息会出现在回退到父亲Activity.onActivityResult()方法,顺着它原本提供的整数定义。
If a child activity fails for any reason (such as crashing), the parent activity will receive a result with the code RESULT_CANCELED.
如果一个孩子Activity因为任何理由(比如崩溃)失败,父亲Activity会接收到一个返回值RESULT_CANCELED。
public class MyActivity extends Activity { ... static final int PICK_CONTACT_REQUEST = 0; public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { // When the user center presses, let them pick a contact. startActivityForResult( new Intent(Intent.ACTION_PICK, new Uri("content://contacts")), PICK_CONTACT_REQUEST); return true; } return false; } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PICK_CONTACT_REQUEST) { if (resultCode == RESULT_OK) { // A contact was picked. Here we will just display it // to the user. startActivity(new Intent(Intent.ACTION_VIEW, data)); } } } }
Saving Persistent State
There are generally two kinds of persistent state than an activity will deal with: shared document-like data (typically stored in a SQLite database using a {@linkplain android.content.ContentProvider content provider}) and internal state such as user preferences.
通常有两种方式进行持久化,SQLite和SharedPreferences。
For content provider data, we suggest that activities use a "edit in place" user model. That is, any edits a user makes are effectively made immediately without requiring an additional confirmation step. Supporting this model is generally a simple matter of following two rules:
对于ContentProvider数据,我们建议Activity使用“适当编辑”用户模型。也就是说,任何的用户编辑是高效即时不需要请求额外确认步骤的。支持这种模型通常只需要依据以下两条规则:
-
When creating a new document, the backing database entry or file for it is created immediately. For example, if the user chooses to write a new e-mail, a new entry for that e-mail is created as soon as they start entering data, so that if they go to any other activity after that point this e-mail will now appear in the list of drafts.
- 当创建一个文件时,后台数据库实体或者文件的创建是即时的。例如,如果一个用户选择写一封新的e-mail,一个新的e-mail实体在它们开始输入数据的时候就创建了,因此如果它们在这个时间点切换去任何其他Activity时,这封e-mail将出现在草稿箱。
-
When an activity's
onPause()
method is called, it should commit to the backing content provider or file any changes the user has made. This ensures that those changes will be seen by any other activity that is about to run. You will probably want to commit your data even more aggressively at key times during your activity's lifecycle: for example before starting a new activity, before finishing your own activity, when the user switches between input fields, etc. - 当一个Activity的onPause()方法被调用,它应该提交到后台ContentProvider或者文件关于用户做了的任何改变。这个确保了那些改变将会被任何其他将要运行的Activity看到。你甚至可能会想要更加粗暴地提交你的数据,在你的Activity生命周期这些关键时间点,例如打开一个Activity之前,结束原有Activity之前,当用户改变输入域时,等等。
This model is designed to prevent data loss when a user is navigating between activities, and allows the system to safely kill an activity (because system resources are needed somewhere else) at any time after it has been paused. Note this implies that the user pressing BACK from your activity does not mean "cancel" -- it means to leave the activity with its current contents saved away. Canceling edits in an activity must be provided through some other mechanism, such as an explicit "revert" or "undo" option.
这个模型的设计是为了用户在Activity间操作时防止数据丢失,并且允许系统在Activity已经paused后任何时候安全地干掉Activity(因为系统资源在别的地方需要)。这暗示着用户在Activity按BACK不意味着“取消” – 意味着保存当前内容并离开Activity。Activity必须通过一些其他机制提供取消编辑,例如一个明确的“恢复”或“撤销”操作。
See the {@linkplain android.content.ContentProvider content package} for more information about content providers. These are a key aspect of how different activities invoke and propagate data between themselves.
查看content包来获取更多关于ContentProvider信息。有关键的一点是不同Activity之间如何调用和传送数据。
The Activity class also provides an API for managing internal persistent state associated with an activity. This can be used, for example, to remember the user's preferred initial display in a calendar (day view or week view) or the user's default home page in a web browser.
Activity类同样提供一个API来管理关联着Activity的内部持久化。举个例子,为了记住用户偏好初始化展示一个日历或者浏览器的用户默认主页。
Activity persistent state is managed with the method {@link #getPreferences}, allowing you to retrieve and modify a set of name/value pairs associated with the activity. To use preferences that are shared across multiple application components (activities, receivers, services, providers), you can use the underlying {@link Context#getSharedPreferences Context.getSharedPreferences()} method to retrieve a preferences object stored under a specific name. (Note that it is not possible to share settings data across application packages -- for that you will need a content provider.)
Activity的持久化用getPreferences(int)来管理,允许你检索和修改关联Activity的键值对。为了使用preferences在多个应用组件间进行共享(Activity,Receiver,Servies,Provider),你可以使用潜在的Context.getSharedPreferences()方法来检索一个preferences对象来保存在特定名字下。(要注意的是,不可能分享设置数据到不同的应用 – 除非你使用ContentProvider。)
Here is an excerpt from a calendar activity that stores the user's preferred view mode in its persistent settings:
这里是一个日历Activity的摘要,用来保存用户偏好的识图模式在它的持久化设置里:
public class CalendarActivity extends Activity { ... static final int DAY_VIEW_MODE = 0; static final int WEEK_VIEW_MODE = 1; private SharedPreferences mPrefs; private int mCurViewMode; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences mPrefs = getSharedPreferences(); mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE); } protected void onPause() { super.onPause(); SharedPreferences.Editor ed = mPrefs.edit(); ed.putInt("view_mode", mCurViewMode); ed.commit(); } }
Permissions
The ability to start a particular Activity can be enforced when it is declared in its manifest's {@link android.R.styleable#AndroidManifestActivity <activity>} tag. By doing so, other applications will need to declare a corresponding {@link android.R.styleable#AndroidManifestUsesPermission <uses-permission>} element in their own manifest to be able to start that activity.
声明在manifest的标签里的Activity能力会被使用。通过在这里设置,其他的应用需要设置关联的元素在它们特定的manifest里才能启用这个Activity。
When starting an Activity you can set {@link Intent#FLAG_GRANT_READ_URI_PERMISSION Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION Intent.FLAG_GRANT_WRITE_URI_PERMISSION} on the Intent. This will grant the Activity access to the specific URIs in the Intent. Access will remain until the Activity has finished (it will remain across the hosting process being killed and other temporary destruction). As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, if the Activity was already created and a new Intent is being delivered to {@link #onNewIntent(Intent)}, any newly granted URI permissions will be added to the existing ones it holds.
当打开一个Activity时你会设置Intent.FLAG_GRANT_READ_URI_PERMISSION 和/或Intent.FLAG_GRANT_WRITE_URI_PERMISSION 在Intent上。这会授予Activity访问特别的URI。访问权会维持到Activity结束(它会维持到持有的进程被干掉和其他临时的毁灭)。从Android 2.3起,如果Activity已经被创建并且一个新的Intent正被传送到onNewIntent(Intent),任何最近的授予的URI权限将被添加到存在的一个Activity上。
See the Security and Permissions document for more information on permissions and security in general.
查看Security和Permissions文档来获取更多关于权限和安全的信息。
Process Lifecycle
The Android system attempts to keep application process around for as long as possible, but eventually will need to remove old processes when memory runs low. As described in Activity Lifecycle, the decision about which process to remove is intimately tied to the state of the user's interaction with it. In general, there are four states a process can be in based on the activities running in it, listed here in order of importance. The system will kill less important processes (the last ones) before it resorts to killing more important processes (the first ones).
安卓系统尝试尽可能长地保持应用进程存在,但是最后当内存低时将会移除旧的进程。正如Activity Lifecycle里讲到的,决定哪个进程被干掉和用户关联程度有关。一般来说,Activity有四种状态,按重要顺序排列在下面。系统在干掉重要性高的进程前会干掉重要性低的进程(最后一个)。
-
The foreground activity (the activity at the top of the screen that the user is currently interacting with) is considered the most important. Its process will only be killed as a last resort, if it uses more memory than is available on the device. Generally at this point the device has reached a memory paging state, so this is required in order to keep the user interface responsive.
- 前台Activity(在屏幕最顶端的Activity,用户当前正在交互的)被认为是重要性最高的。它的进程最后才会被杀,如果要使用的内存比留下的更多时。通常来说这时设备是要即时响应用户的。
-
A visible activity (an activity that is visible to the user but not in the foreground, such as one sitting behind a foreground dialog) is considered extremely important and will not be killed unless that is required to keep the foreground activity running.
- 可见Activity(Activity对用户来说可见但是不在前台,例如在一个前台对话框后面)被认为是极其重要的并且不会被干掉除非要保持前台Activity运行而逼不得已。
-
A background activity (an activity that is not visible to the user and has been paused) is no longer critical, so the system may safely kill its process to reclaim memory for other foreground or visible processes. If its process needs to be killed, when the user navigates back to the activity (making it visible on the screen again), its {@link #onCreate} method will be called with the savedInstanceState it had previously supplied in {@link #onSaveInstanceState} so that it can restart itself in the same state as the user last left it.
- 后台Activity(对用户来说不可见而且已经处于paused)不再危险,所以系统可能会安全地干掉它的进程来回收利用内存给其他后台或可见的进程使用。如果它被干掉,当用户回到这个Activity时,Activity会通过onSaveInstanceState(Bundle)保存的数据,重新调用onCreate(Bundle)方法来重启并且恢复到原本状态。
-
An empty process is one hosting no activities or other application components (such as {@link Service} or {@link android.content.BroadcastReceiver} classes). These are killed very quickly by the system as memory becomes low. For this reason, any background operation you do outside of an activity must be executed in the context of an activity BroadcastReceiver or Service to ensure that the system knows it needs to keep your process around.
- 一个空进程是指不持有Activity和其他应用组件(例如Service或BroadcastReceiver类)。这些在系统内存低时会很快被干掉。因此,任何在Activity之外的后台操作必须在Activity的BroadcastReceiver或者Service的context执行,来确保系统知道它需要保持你的进程。
Sometimes an Activity may need to do a long-running operation that exists independently of the activity lifecycle itself. An example may be a camera application that allows you to upload a picture to a web site. The upload may take a long time, and the application should allow the user to leave the application while it is executing. To accomplish this, your Activity should start a {@link Service} in which the upload takes place. This allows the system to properly prioritize your process (considering it to be more important than other non-visible applications) for the duration of the upload, independent of whether the original activity is paused, stopped, or finished.
有时候,Activity可能需要独立于生命周期之外做一些长时间运行的操作。一个例子是,一个相机应用允许你上传照片到网站。上传可能要耗大量时间,而且应用应该允许用户在它上传的时候离开。为了完成这个,你的Activity应该开启一个Service来代替Activity上传。这个允许系统适当地给你的进程在上传期间排优先级(比其他不可见的应用具有更高的重要性),独立于Activity原始的paused,stopped或者finished。
参考博客: