【翻译】Activity

来源:互联网 发布:linux子目录权限设置 编辑:程序博客网 时间:2024/06/08 04:11

参考地址:https://developer.android.com/reference/android/app/Activity.html

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 setContentView(View). 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 windowIsFloating set) or embedded inside of another activity (using ActivityGroup). There are two methods almost all subclasses of Activity will implement:
Activity是用户可以简单粗暴进行使用的东西。几乎所有的Activity都与用户关联,所以你可以通过setContentView(View)来把你的UI元素放置到Activity来让Activity创建一个窗口。Activity经常是以全屏形式展现给世人,但是其实它还可以被用在其他方面,例如悬浮窗(通过windowIsFloating主题设置)或者嵌入到另一个Activity(通过ActivityGroup)。有两个几乎所有Activity的子类都会实现的方法:

onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.
onCreate(Bundle)是初始化Activity的地方。最重要的是,你会经常在这里调用setContentView(int)来设置布局,调用findViewById(int)类来找到对应的小部件进行动态部署。

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 ContentProvider holding the data).
onPause()是离开Activity时和用户交互的地方。最重要的是,用户的任何改变应该在这个时间点之前完成(通常是ContentProvider在搞数据)。

To be of use with Context.startActivity(), all activity classes must have a corresponding declaration in their package’s AndroidManifest.xml.
通过使用Context.startActivity(),所有的Activity类必须在AndroidManifest.xml有一个对应声明的包名。

Topics covered here:
主题包括下面几个:

Fragments
Activity Lifecycle
Configuration Changes
Starting Activities and Getting Results
Saving Persistent State
Permissions
Process Lifecycle


Developer Guides

The Activity class is an important part of an application’s overall lifecycle, and the way activities are launched and put together is a fundamental part of the platform’s application model. For a detailed perspective on the structure of an Android application and how activities behave, please read the Application Fundamentals and Tasks and Back Stack developer guides.
Activity类是应用整个声明周期很重要的一部分,Activity的启动和放在一起的方式是平台应用模型的基础部分。对于Android application的结构和Activity的行为的详细观点,可以参考开发者指引里的Applicaiton Fundamentals和Tasks以及Back Stack。

You can also find a detailed discussion about how to create activities in the Activities developer guide.
你也可以在Activities开发者指引里找到关于如何创建Activity的详细套路。


Fragments

Starting with HONEYCOMB, Activity implementations can make use of the Fragment class to better modularize their code, build more sophisticated user interfaces for larger screens, and help scale their application between small and large screens.
Android3.0开始出现,Activity使用Fragment类可以更好的模块化代码,对大屏幕可以建立更发杂的用户接口,以及可以帮助适配应用的小屏和大屏。


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.
Acitvity在系统里使用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.
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。一个paused的Activity也是完全活着的(它维持着所有的状态以及成员信息并且保持依附在window manager上),但内存不足时可以被系统干掉。

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状态为paused或者stopped,系统可以通过调用它结束或者直接干掉它的进程来将它从内存中清理掉。当它再一次展现在世人面前时,它必须完全重启和恢复到之前的状态。

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 onCreate(Bundle) through to a single final call to 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(Bundle),知道最后单一的调用onDestroy()。Activity会在onCreate做所有关于“全局的”状态步骤,并且在onDestroy释放所有剩余的资源。例如,如果需要一个后台运行的线程从网络上下载数据,可以在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 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()注册广播来监控影响你的UI的变化,并且在onStop()里反注册广播,因为在此时用户已经看不到你展示的东西了。onStart()和onStop()方法可以随着Activity可见和隐藏被多次调用。

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 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 onCreate(Bundle) to do their initial setup; many will also implement 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(Bundle)来做它们的初始化安装;许多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 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 onStart(). No onStart() onRestart() Called after your activity has been stopped, prior to it being started again.Always followed by onStart() No onStart() onStart() Called when the activity is becoming 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() 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 onPause(). No 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 onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user. Pre-HONEYCOMB onResume() or 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 onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away. Yes onRestart() or onDestroy() onDestroy() The final call you receive before your activity is destroyed. This can happen 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 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 onPause() method to write any persistent data (such as user edits) to storage. In addition, the method 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 onCreate(Bundle) 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 onPause() instead of onSaveInstanceState(Bundle) 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 HONEYCOMB vs. those targeting prior platforms. Starting with Honeycomb, an application is not in the killable state until its onStop() has returned. This impacts when onSaveInstanceState(Bundle) may be called (it may be safely called after onPause() and allows and application to safely wait until 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 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 onPause(), onStop(), and onDestroy() as appropriate. If the activity had been in the foreground or visible to the user, once 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 onSaveInstanceState(Bundle).
除非你特别指定,否则,配置的改变(例如横竖屏,语言,输入法等等)将会导致当前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 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 onConfigurationChanged(Configuration) method instead of being restarted. If a configuration change involves any that you do not handle, however, the activity will still be restarted and onConfigurationChanged(Configuration) will not be called.
在一些特别的情况下,你可能需要忽略基于一个或多个类型配置改变带来的重启。通过manifest文件里的android:configChanges属性来处理就可以。对于任何配置改变,你会接收到当前Activity的onConfigurationChanged(Configuration)方法调用而不是重启。如果一个配置改变调用牵涉到任何你不处理的东西,Activity仍然会重启而不调用onConfigurationChanged(Configuration)。


Starting Activities and Getting Results

The startActivity(Intent) 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 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 startActivityForResult(Intent, int) version with a second integer parameter identifying the call. The result will come back through your onActivityResult(int, int, Intent) method.
有时候你想要从一个Activity的结束获得一个结果。例如,你可能打开一个Activity让用户从联系人列表里选一个人;当选择结束的时候,会返回被选择的人。为此,你可以调用startActivityForResult(Intent,int)第二个整数型参数辨识调用者。通过onActivityResult(int,int,Intent)方法会返回结果。

When an activity exits, it can call 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 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 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 getPreferences(int), 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 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 tag. By doing so, other applications will need to declare a corresponding element in their own manifest to be able to start that activity.
声明在manifest的标签里的Activity能力会被使用。通过在这里设置,其他的应用需要设置关联的元素在它们特定的manifest里才能启用这个Activity。

When starting an Activity you can set Intent.FLAG_GRANT_READ_URI_PERMISSION and/or 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 GINGERBREAD, if the Activity was already created and a new Intent is being delivered to 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 onCreate(Bundle) method will be called with the savedInstanceState it had previously supplied in onSaveInstanceState(Bundle) 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 Service or 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 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。

0 0