Android官网Activities文档翻译

An Activity is an application component that provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface. The window typically fills the screen, but may be smaller than the screen and float on top of other windows.

activity是一个可以提供屏幕的应用组件,用户可与该界面交互实现相应的功能,例如打电话、拍照、发邮件或查看地图等。每一个activity都会有一个窗口用于实现其用户界面。这个窗口通常情况下会铺满屏幕,但是有时也会比屏幕更小并且漂浮在其它窗口的上面。

An application usually consists of multiple activities that are loosely bound to each other. Typically, one activity in an application is specified as the "main" activity, which is presented to the user when launching the application for the first time. Each activity can then start another activity in order to perform different actions. Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack"). When a new activity starts, it is pushed onto the back stack and takes user focus. The back stack abides to the basic "last in, first out" stack mechanism, so, when the user is done with the current activity and presses the Back button, it is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is discussed more in the Tasks and Back Stack document.)

一个应用通常由多个相互分离又彼此存在逻辑关系的activity组成。其中,应用中的某个activity被指定为“main”activity,该activity会在应用第一次启动时展现给用户。为了实现不同的功能,每一个activity都可以启动相应的另一个activity。当新的activity被启动的时候,前面的activity都会被中断,但是系统会将该之前的activity保存到栈(回退栈)中。当一个新的activity被启动,该activity就会被放到回退栈的栈顶并且获取到用户焦点。这个回退栈遵循基本的“先进后出,后进先出”的栈机制,因此,当用户完成当前activity的操作并且按返回按钮时,该activity就会被从回退栈中取出(并且销毁)然后之前的activity会再次获取焦点。(更多关于回退栈的内用参考"Tasks and Back Stack"相关文档。)

When an activity is stopped because a new activity starts, it is notified of this change in state through the activity's lifecycle callback methods. There are several callback methods that an activity might receive, due to a change in its state—whether the system is creating it, stopping it, resuming it, or destroying it—and each callback provides you the opportunity to perform specific work that's appropriate to that state change. For instance, when stopped, your activity should release any large objects, such as network or database connections. When the activity resumes, you can reacquire the necessary resources and resume actions that were interrupted. These state transitions are all part of the activity lifecycle.

当因启动新的activity而中断当前activity时,会通过activity的回调方法来通知这个状态的变化。当activity的状态发生变化时,该activity可能会执行一系列回调方法,例如创建activity、activity不可见、activity获取焦点或者销毁activity。每一个回调方法都可以针对其状态的变化自定义一些相应的功能。例如,当activity不可见时,你的activity应该释放一些比较占内存的对象,像网络连接或数据库连接等。当该activity重新获取到焦点时你可以重新获取这些必要的资源和恢复之前中断的操作。这些状态的变化都是activity生命周期的一部分。

The rest of this document discusses the basics of how to build and use an activity, including a complete discussion of how the activity lifecycle works, so you can properly manage the transition between various activity states.

后面会讨论如何创建和使用activity的基本内容,包括activity的生命周期是如何工作的完整的讨论,通过这些你可以管理多个activity间的状态转化。

Creating an Activity


To create an activity, you must create a subclass of Activity (or an existing subclass of it). In your subclass, you need to implement callback methods that the system calls when the activity transitions between various states of its lifecycle, such as when the activity is being created, stopped, resumed, or destroyed. The two most important callback methods are:

要创建一个activity,你必须创建一个activity(或者已经存在的activity的子类)的子类。在你定义的子类你需要实现activity生命周期中多个状态发生变化时系统要调用的一些回调方法,例如,当activity被创建时、不可见时、获取焦点时或者被销毁时。其中两个最重要的回调方法是:

onCreate()

You must implement this method. The system calls this when creating your activity. Within your implementation, you should initialize the essential components of your activity. Most importantly, this is where you must call setContentView() to define the layout for the activity's user interface.

你必须实现这个方法。当创建activity时系统会调用该放过。在该方法中你应该初始化一些该activity的必要的组件。更重要的是,你必须调用setContentView()方法来指定该activity的用户界面的布局。

onPause()

The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).

当用户开始离开你的activity时系统会首先调用这个方法(尽管这并不意味着activity将会被销毁)。通常在这个方法中你应该保存一些用户操作的重要数据(因为用户可能不会再回到该activity了)。

There are several other lifecycle callback methods that you should use in order to provide a fluid user experience between activities and handle unexpected interuptions that cause your activity to be stopped and even destroyed. All of the lifecycle callback methods are discussed later, in the section about Managing the Activity Lifecycle.

在各个activity交互以及可能引起activity的中断甚至销毁时,可以调用activity的其它的生命周期的方法实现流畅的用户体验。所有这些方法都会在“Managing the Activity Lifecycle”章节中讨论。

Implementing a user interface

The user interface for an activity is provided by a hierarchy of views—objects derived from the View class. Each view controls a particular rectangular space within the activity's window and can respond to user interaction. For example, a view might be a button that initiates an action when the user touches it.

用户界面由一些列有层级结构的view组件组成(这些view组件都是View的子类)。每一个view组件控制着一个activity窗口中的特定的矩形区域并且能够响应用户操作。当用户按下一个Button组件时可以传递用户的这个操作。

Android provides a number of ready-made views that you can use to design and organize your layout. "Widgets" are views that provide a visual (and interactive) elements for the screen, such as a button, text field, checkbox, or just an image. "Layouts" are views derived from ViewGroup that provide a unique layout model for its child views, such as a linear layout, a grid layout, or relative layout. You can also subclass the View and ViewGroupclasses (or existing subclasses) to create your own widgets and layouts and apply them to your activity layout.

Android系统提供了许多线程的view组件,你可以使用这些组件组织和设计你的布局。"Widgets"是一些向屏幕提供可见的(和可交互的)元素的视图,例如按钮、文本框、checkbox或图片等。"Layouts"是ViewGroup的子类,可以为其内部的布局提供唯一的布局模型,例如线性布局,格子布局或者相对布局等。你也可以自定义一些View(或已存在的子类)或ViewGroup(或已存在的子类)的子类去创建你自己的组件或布局。

The most common way to define a layout using views is with an XML layout file saved in your application resources. This way, you can maintain the design of your user interface separately from the source code that defines the activity's behavior. You can set the layout as the UI for your activity with setContentView(), passing the resource ID for the layout. However, you can also create new Views in your activity code and build a view hierarchy by inserting new Views into a ViewGroup, then use that layout by passing the rootViewGroup to setContentView().

最常用的定义布局的方式是使用保存在你的应用资源文件中的xml布局文件。通过这种方式,你可以将你的用户界面资源与描述activity逻辑的资源代码区别开,方便维护。你可以调用setContetnView()方法指定你用户界面的布局文件,只需将布局的资源id传递给setContentView()即可。你也可以在activity代码中创建视图然后构建一个具有层级结构的布局插入到ViewGroup,然后将这个ViewGroup放到setContetnView()方法中。

For information about creating a user interface, see the User Interface documentation.

关于创建用户界面的更多内容参考“User Interface”相关文档。

Declaring the activity in the manifest

You must declare your activity in the manifest file in order for it to be accessible to the system. To declare your activity, open your manifest file and add an <activity> element as a child of the <application> element. For example:

为了让你的activity能够被系统访问,你必须在清单文件中声明它。在清单文件中给<application>元素添加<activity>子元素声明activity,例如:

<manifest ... >
  <application ... >
      <activity android:name=".ExampleActivity" />
      ...
  </application ... >
  ...
</manifest >

There are several other attributes that you can include in this element, to define properties such as the label for the activity, an icon for the activity, or a theme to style the activity's UI. The android:name attribute is the only required attribute—it specifies the class name of the activity. Once you publish your application, you should not change this name, because if you do, you might break some functionality, such as application shortcuts (read the blog post, Things That Cannot Change).

在<activity>元素中还可以指定一些其他的属性,例如指定activity的标题、图标、UI的样式和主题等。其中android:name属性是必须要指定的-它指定activity的全类名。一旦你发布了你的应用,你就不应该再改变这个属性,因为如果改变了你可能会破坏一些功能,例如应用的快捷方式(参考博客“Things That Cannot Change”)。

See the <activity> element reference for more information about declaring your activity in the manifest.

看"<activity>"连接了解更多在清单文件中声明activity的内容。

Using intent filters

An <activity> element can also specify various intent filters—using the <intent-filter> element—in order to declare how other application components may activate it.

一个<activity>也可以用<intent-filter>元素指定各种意图过滤器,用于声明其它应用组件如何激活它。

When you create a new application using the Android SDK tools, the stub activity that's created for you automatically includes an intent filter that declares the activity responds to the "main" action and should be placed in the "launcher" category. The intent filter looks like this:

当你用Android开发工具创建一个新的应用的时候,自动生成的根activity包含一个意图过滤器声明了该activity会对"main"action做出响应并且会被放置在"launcher"category。如下所示:

<activity android:name=".ExampleActivity" android:icon="@drawable/app_icon">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

The <action> element specifies that this is the "main" entry point to the application. The <category> element specifies that this activity should be listed in the system's application launcher (to allow users to launch this activity).

<action>元素表明当前activity是这个应用的"main"入口点。<category>元素表明该activity将被登记在系统的应用加载器上(允许用户加载该activity)。

If you intend for your application to be self-contained and not allow other applications to activate its activities, then you don't need any other intent filters. Only one activity should have the "main" action and "launcher" category, as in the previous example. Activities that you don't want to make available to other applications should have no intent filters and you can start them yourself using explicit intents (as discussed in the following section).

如果你希望你的activity只能在你应用中自行控制并且不允许其它应用激活你的activity,你只需不添加<intent-filter>即可。之前的例子表明,一个应用只允许有一个activity有"main"action和"launcher"category。如果你不想其它应用启动你的activity只需取消<intent-filter>即可,然后你可以通过显式意图启动该activity(下面的内容会讲到)。

However, if you want your activity to respond to implicit intents that are delivered from other applications (and your own), then you must define additional intent filters for your activity. For each type of intent to which you want to respond, you must include an <intent-filter> that includes an <action> element and, optionally, a<category> element and/or a <data> element. These elements specify the type of intent to which your activity can respond.

如果你希望其它应用也可以通过隐式意图启动你的activity,你必须为该activity指定<intent-filter>。对于某一个你想响应的Intent,你必须指定一个<intent-filter>,该<intent-filter>包含一个<action>元素,<category>元素和<data>元素根据需要可有可无。这些元素就声明了你的activity可以响应的类型。

For more information about how your activities can respond to intents, see the Intents and Intent Filtersdocument.

更多关于activity如何响应intent的内容参考“Intents and Intent Filters”文档。

Starting an Activity


You can start another activity by calling startActivity(), passing it an Intent that describes the activity you want to start. The intent specifies either the exact activity you want to start or describes the type of action you want to perform (and the system selects the appropriate activity for you, which can even be from a different application). An intent can also carry small amounts of data to be used by the activity that is started.

你可以调用startActivity()方法来启动另一个activity,该方法的参数是描述了你想启动的activity的intent。这个Intent可以指定你想启动的具体的activity也可以描述你想操作的action的类型(系统会根据你指定的action的类型选择启动合适的activity,该activity可能来自不同的应用)。Intent也可以携带少量的数据到待启动的activity。

When working within your own application, you'll often need to simply launch a known activity. You can do so by creating an intent that explicitly defines the activity you want to start, using the class name. For example, here's how one activity starts another activity named SignInActivity:

在你应用的内部,你通常只需简单的加载一个已知的activity即可。你可以创建一个Intent然后用activity的类名明确的指定你要启动的activity即可。案例如下:

Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);

However, your application might also want to perform some action, such as send an email, text message, or status update, using data from your activity. In this case, your application might not have its own activities to perform such actions, so you can instead leverage the activities provided by other applications on the device, which can perform the actions for you. This is where intents are really valuable—you can create an intent that describes an action you want to perform and the system launches the appropriate activity from another application. If there are multiple activities that can handle the intent, then the user can select which one to use. For example, if you want to allow the user to send an email message, you can create the following intent:

然而,你的应用有时希望去执行一些action,例如发邮件、发短信、拍照等。此时,你的应用可能没有这样的activity去执行这些action,因此你可以启动设备上的其它应用中可以执行该action的activity。从这里可以看出Intetn的重要性-你可以创建一个描述你想操作的action的intent然后系统会从其它应用中加载相应的activity。如果该intent对应过个activity,你可以从中选择一个打开(系统会弹出一个选择框)。例如,如果你的应用允许用户发送邮件,你可以创建下面这样的intent:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);
startActivity(intent);

The EXTRA_EMAIL extra added to the intent is a string array of email addresses to which the email should be sent. When an email application responds to this intent, it reads the string array provided in the extra and places them in the "to" field of the email composition form. In this situation, the email application's activity starts and when the user is done, your activity resumes.

其中额外添加到intent的EXTRA_EMAIL是一个你想发送的邮件地址的字符串数组。当一个邮件应用做出响应,就会读取该字符串数组并将其中的email地址放到收件人的输入框中。此时邮件的activity启动,当用户操作完成后,你的activity重新获取焦点。

Starting an activity for a result

Sometimes, you might want to receive a result from the activity that you start. In that case, start the activity by calling startActivityForResult() (instead of startActivity()). To then receive the result from the subsequent activity, implement the onActivityResult() callback method. When the subsequent activity is done, it returns a result in an Intent to your onActivityResult() method.

有时,你可能会希望从你打开的activity中获取返回数据。此时,你应该调用startActivityForResult()方法启动activity,而不是调用startActivity()方法。然后在onActivityResult()方法中接收后来的activity返回的数据。后来的activity关闭后会将返回的数据放入intent传递到onActivityResult()方法中。

For example, perhaps you want the user to pick one of their contacts, so your activity can do something with the information in that contact. Here's how you can create such an intent and handle the result:

例如,也许你希望用户可以选择一个联系人,下面案例展示了如何创建这样一个intent并且获取返回值:

private void pickContact() {
    // Create an intent to "pick" a contact, as defined by the content provider URI
    Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
    startActivityForResult(intent, PICK_CONTACT_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // If the request went well (OK) and the request was PICK_CONTACT_REQUEST
    if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {
        // Perform a query to the contact's content provider for the contact's name
        Cursor cursor = getContentResolver().query(data.getData(),
        new String[] {Contacts.DISPLAY_NAME}, null, null, null);
        if (cursor.moveToFirst()) { // True if the cursor is not empty
            int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
            String name = cursor.getString(columnIndex);
            // Do something with the selected contact's name...
        }
    }
}

This example shows the basic logic you should use in your onActivityResult() method in order to handle an activity result. The first condition checks whether the request was successful—if it was, then the resultCodewill be RESULT_OK—and whether the request to which this result is responding is known—in this case, therequestCode matches the second parameter sent with startActivityForResult(). From there, the code handles the activity result by querying the data returned in an Intent (the data parameter).

这个案例演示了为了获取activity的返回值你应该在onActivityResult()方法中实现的基本的逻辑。首先检查请求是否成功,如果请求成功,则resultCode应该是RESULT_OK,再检查这个请求结果是不是当前activity发起后返回的,如果是,则requestCode应该和startActivityForResult()的第二个参数相同。返回值存放在onActivityResult()的第三个参数的data数据中。

What happens is, a ContentResolver performs a query against a content provider, which returns a Cursor that allows the queried data to be read. For more information, see the Content Providers document.

之后,使用ContentResolver查询内容提供者会返回一个Cursor,可以从Cursor中读取数据。更多内容看“Content Providers”相关文档。

For more information about using intents, see the Intents and Intent Filters document.

更多如何使用intent的内容,参考“Intents and Intent Filters”相关文档。

Shutting Down an Activity


You can shut down an activity by calling its finish() method. You can also shut down a separate activity that you previously started by calling finishActivity().

你可以调用finish()方法关闭activity,也可以调用finishActivity()方法关闭之前启动的activity。

Note: In most cases, you should not explicitly finish an activity using these methods. As discussed in the following section about the activity lifecycle, the Android system manages the life of an activity for you, so you do not need to finish your own activities. Calling these methods could adversely affect the expected user experience and should only be used when you absolutely do not want the user to return to this instance of the activity.

提示:大多说情况下,你不必用这些方法关闭一个具体的activity。按照下面关闭activity生命周期的讨论,Android系统会替你管理activity的生命周期。调用这些方法可能会影响用户体验,只有当你确定不希望用户返回到该activity时才调用这些关闭activity的方法。

Managing the Activity Lifecycle


Managing the lifecycle of your activities by implementing callback methods is crucial to developing a strong and flexible application. The lifecycle of an activity is directly affected by its association with other activities, its task and back stack.

要开发出健壮灵活的应用,通过实现activity生命周期的各个回调方法来管理activity的生命周期非常关键。activity与其它activity的关系以及activity的task和back task直接影响activity的生命周期。

An activity can exist in essentially three states:

一个activity可以在本质上存在三种状态:

Resumed

The activity is in the foreground of the screen and has user focus. (This state is also sometimes referred to as "running".)

activity在屏幕的前台并且获取用户焦点。(这个状态有时也指"running")。

Paused

Another activity is in the foreground and has focus, but this one is still visible. That is, another activity is visible on top of this one and that activity is partially transparent or doesn't cover the entire screen. A paused activity is completely alive (the Activity object is retained in memory, it maintains all state and member information, and remains attached to the window manager), but can be killed by the system in extremely low memory situations.

另一个activity在屏幕的前端并且获取到用户焦点,但是这个activity仍然可见。也就是说另一个activity在这个activity的上面可见,并且是半透明的或者没有铺满屏幕。处于"Paused"状态的activity仍然是激活状态(该activity被保存在内存,它维持所有的状态和成员信息,并且仍然依附于窗口管理器),但是当系统内存严重不足时会被回收。

Stopped

The activity is completely obscured by another activity (the activity is now in the "background"). A stopped activity is also still alive (the Activity object is retained in memory, it maintains all state and member information, but is not attached to the window manager). However, it is no longer visible to the user and it can be killed by the system when memory is needed elsewhere.

该activity完全被其它activity覆盖(该activity当前运行在后台)。处于"stopped"状态的activity仍然是激活状态(该activity被保存在内存,它维持所有的状态和成员信息,但是并不依附于窗口管理器)。另外,用户看不见该activity并且当系统需要更多内存时会被易被系统回收。

If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling itsfinish() method), or simply killing its process. When the activity is opened again (after being finished or killed), it must be created all over.

如果一个activity处于"paused"或"stopped"状态,通过调用activity的finish()方法或者杀死其进程可将其从内存中回收。当这个activity被再次打开(被finish或杀死进程后),会重新创建该activity。

Implementing the lifecycle callbacks

When an activity transitions into and out of the different states described above, it is notified through various callback methods. All of the callback methods are hooks that you can override to do appropriate work when the state of your activity changes. The following skeleton activity includes each of the fundamental lifecycle methods:

当activity的状态发生变化时,activity会通过各个回调方法接收到该变化的通知。你可以重写各个回调方法在状态变化时实现相应的功能。下边的案例包含了各个生命周期的方法:

public class ExampleActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // The activity is being created.
    }
    @Override
    protected void onStart() {
        super.onStart();
        // The activity is about to become visible.
    }
    @Override
    protected void onResume() {
        super.onResume();
        // The activity has become visible (it is now "resumed").
    }
    @Override
    protected void onPause() {
        super.onPause();
        // Another activity is taking focus (this activity is about to be "paused").
    }
    @Override
    protected void onStop() {
        super.onStop();
        // The activity is no longer visible (it is now "stopped")
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // The activity is about to be destroyed.
    }
}

Note: Your implementation of these lifecycle methods must always call the superclass implementation before doing any work, as shown in the examples above.

提示:实现这些生命周期的方法你必须先调用父类的方法在实现自己的业务逻辑,正如上面的案例那样。

Taken together, these methods define the entire lifecycle of an activity. By implementing these methods, you can monitor three nested loops in the activity lifecycle:

总之,这些方法定义了activity的完整的生命周期。通过实现这些方法,你可以检测activity的三个嵌套的周期。

  • The entire lifetime of an activity happens between the call to onCreate() and the call to onDestroy(). Your activity should perform setup of "global" state (such as defining layout) in onCreate(), and release all remaining resources in onDestroy(). For example, if your activity has a thread running in the background to download data from the network, it might create that thread in onCreate() and then stop the thread inonDestroy().
  • 完整的生命周期包括onCreate(),onStart(),onResume(),onPause(),onStop(),onDestroy()。你的activity应该着眼去全局,例如在onCreate()中指定布局文件,在onDestroy中释放剩余资源。再例如,如果你的activity在后台有一个访问网络下载数据的线程,你可以在onCreate()方法中创建线程然后在onDestroy()方法中终止线程。
  • The visible lifetime of an activity happens between the call to onStart() and the call to onStop(). During this time, the user can see the activity on-screen and interact with it. For example, onStop() is called when a new activity starts and this one is no longer visible. Between these two methods, you can maintain resources that are needed to show the activity to the user. For example, you can register aBroadcastReceiver in onStart() to monitor changes that impact your UI, and unregister it in onStop()when the user can no longer see what you are displaying. The system might call onStart() and onStop()multiple times during the entire lifetime of the activity, as the activity alternates between being visible and hidden to the user.

  • 可视生命周期包括onStart(),onResume().onPause(),onStop()。再此期间,用户可以在屏幕上看到该activity并且可与其交互。例如,当新的activity被启动,这个activity不再可见时调用onStop()方法。在可视生命周期中你可以维护需要在activity中展示给用户的资源。例如,你可以在onStart()方法中注册一个BroadCastReceiver来监测影响你UI的变化,当用户看不到你在activity中展示的内容时你可以在onStop()方法中取消注册。activity在可见和不可见交替的过程中,在activity的整个生命周期中系统可能会多次调用onStart()和onStop()方法。

  • The foreground lifetime of an activity happens between the call to onResume() and the call to onPause(). During this time, the activity is in front of all other activities on screen and has user input focus. An activity can frequently transition in and out of the foreground—for example, onPause() is called when the device goes to sleep or when a dialog appears. Because this state can transition often, the code in these two methods should be fairly lightweight in order to avoid slow transitions that make the user wait.

  • 前台生命周期包括onResume()和onPause()。在此期间,这个activity在屏幕上所有activity的前面并且获取到用户焦点。activity可以频繁的在前后台进行切换-例如,当设备休眠或者弹出对话框时activity的onPause()方法被调用。正是因为这种状态的频繁转化,为了避免转换的缓慢导致用户等待尽量在这两个方法中实现轻量级且不耗时的代码。

Figure 1 illustrates these loops and the paths an activity might take between states. The rectangles represent the callback methods you can implement to perform operations when the activity transitions between states.

图一说明了一个activity在各个状态转变过程中可能经历的各个闭环或者运行轨迹。矩形代表了当activity的状态发生变化时你可以去重写的一些回调方法,通过这些回调方法你可以实现相应的功能。

Figure 1. The activity lifecycle.

The same lifecycle callback methods are listed in table 1, which describes each of the callback methods in more detail and locates each one within the activity's overall lifecycle, including whether the system can kill the activity after the callback method completes.

上述上面周期的回调方法都被列入到了表1,该表更加详细的描述了每一个回调方法的含义及其在整个生命周期中所处的位置,包括这个回调方法执行完成后系统是否可以杀死该activity。

Table 1. A summary of the activity lifecycle's callback methods.

Method Description Killable after? 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().

第一次创建activity时执行该方法。通常在这个方法中做一些常规的静态设置,例如创建视图(界面),绑定待展示的数据等等。这个方法的参数是一个包含该activity先前状态的Bundle对象(前提是该activity有且捕获到了先前的状态)(参考后面的"aving Activity State"的内容)。
总是在其后执行onCreate()方法。

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

Always followed by onStart()

该方法在onStop()方法之后执行,也就是说在该activity即将再次被启动之前执行。
总是在其后执行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.

在用户可见之前调用该方法。如果该activity要显示到前台则执行执行完该方法后会执行onResume()方法,如果该activity将要处于隐藏状态则执行完该方法后执行onStop()方法(例如如果在onStart()方法中调用finish()方法,则执行顺序为onStart() > onStop() > onDestroy())。

No onResume() 
or
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().

当该activity开始可以与用户交互(获取焦点)时会执行onResume()。此时,该activity处于任务栈的顶部,用户可以操作该activity。
该方法之后总是执行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.

当系统即将启动另一个activity时会调用当前activity的onPause()方法。 这个方法通常用于将未保存的变化保存到持久化数据,停止动画或者其它比较销毁内存的东西等等(因为onPause()方法执行完后进程就有可能被回收,因此尽早保存数据)。无论在该方法中执行什么操作都应该是比较短暂的操作,因为只有当该方法执行完后下一个activity才能启动并显示。
如果该activity返回到前台会执行onResume()方法(前台生命周期:onResume() > onPause())。如果之后该activity用户不可见则执行onStop()方法。

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 byonDestroy() if this activity is going away.

当该activity用户不可见时执行该onStop()方法。当该activity即将被销毁时或者另一个(已经存在的或者新创建的)activity已经启动并且完全掩盖该activity时都会执行该方法。 
如果该activity即将重新获取焦点会接着执行onRestart(),或者如果该activity即将消失会执行onDestroy()方法。

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

在该activity被销毁之前执行onDestroy()方法。这是activity能够收到的生命周期中之后执行的方法。当调用activity的finish()方法或者系统暂时销毁该activity实例以节省空间时都会执行该onDestroy()方法。通过调用isFinishing()可以判读出是这两种情况的哪一种。.

Yes nothing

The column labeled "Killable after?" 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 are marked "yes": (onPause()onStop(), and onDestroy()). Because onPause() is the first of the three, once the activity is created, onPause() is the last method that's guaranteed to be called before the process can be killed—if the system must recover memory in an emergency, then onStop() and onDestroy() might not be called. Therefore, you should use onPause() to write crucial persistent data (such as user edits) to storage. However, you should be selective about what information must be retained during onPause(), because any blocking procedures in this method block the transition to the next activity and slow the user experience.

列“Killable after”表明在该生命周期的回调方法执行完成后是否可以在不执行activity任何代码的情况下(由系统完成)系统可以销毁该activity所在的进程。其中的onPause(),onStop(),onDestroy()都被标记为"yes"。其中onPause()方法是三者中的第一个方法,因此,一旦activity被创建,在onStop()和onDestroy()还没有被调用并且系统急需回收内存的情况下,onPause()方法就是系统可以回收该activity所在进程之前一定会执行的最后一个方法。因此,应该在onPause()方法中保存关键的持久化数据(例如用户编辑的一些内容)到存储空间(手机内存或sd卡中)。然而在onPause()方法中你应该尽量挑选一些关键的信息去保存,因为该方法中任何耗时的程序都会阻塞向下一个activity的跳转并且用户会感到卡慢。

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 killable from the time onPause() returns to the timeonResume() is called. It will not again be killable until onPause() is again called and returns.

标记了"NO"的列保证了该方法被调用时其所在的进程不会被系统回收。因此,从onPause()执行结束到onResume()被调用这期间该activity都可能被系统回收(onPause()>onResume())。直到onPause()方法再次被调用并执行结束,activity所在进程又可能被系统回收。

Note: An activity that's not technically "killable" by this definition in table 1 might still be killed by the system—but that would happen only in extreme circumstances when there is no other recourse. When an activity might be killed is discussed more in the Processes and Threading document.

注意:按照表一所描述的,这个activity并不是严格意义上的"killable",只是有可能被系统回收,而且只有当内存资源极度匮乏的时候才有可能被销毁。更多详细内容参考"Processes and Threading"文档。

Saving activity state

The introduction to Managing the Activity Lifecycle briefly mentions that when an activity is paused or stopped, the state of the activity is retained. This is true because the Activity object is still held in memory when it is paused or stopped—all information about its members and current state is still alive. Thus, any changes the user made within the activity are retained so that when the activity returns to the foreground (when it "resumes"), those changes are still there.

前面"Managing the Activity Lifecycle"的章节简短介绍了当activity处于"paused"状态或者"stopped"状态时,activity的状态将会被保存。确实是这样,因为当activity处于"paused"状态或者"stopped"状态时activity实例仍然在内存中存在,其所有的成员信息以及状态仍然存活。因此,用户在该activity做出的任何变化都会被保存,所以当该activity返回到前台(获取到焦点)时,这些变化仍然存在。(这一段所描述的情况是简单的可见 > 不可见 > 可见的过程,不是activity被销毁的情况,即再次可见时不执行onCreate())

However, when the system destroys an activity in order to recover memory, the Activity object is destroyed, so the system cannot simply resume it with its state intact. Instead, the system must recreate the Activity object if the user navigates back to it. Yet, the user is unaware that the system destroyed the activity and recreated it and, thus, probably expects the activity to be exactly as it was. In this situation, you can ensure that important information about the activity state is preserved by implementing an additional callback method that allows you to save information about the state of your activity: onSaveInstanceState().

然而,当系统为了释放内存而销毁activity时,这个activity对象将被销毁,因此,系统不能做到径直地恢复该activity之前完整的状态。而是当用户再次返回到该activity时系统会重新创建这个activity对象。但是,用户并不会意识到系统销毁并重新创建了和之前一模一样的activity。基于这种情况,你可以调用额外的允许你保存activity状态信息的回调方法onSaveInstanceState()来保存activity的重要状态数据(用于重建activity)。

The system calls onSaveInstanceState() before making the activity vulnerable to destruction. The system passes this method a Bundle in which you can save state information about the activity as name-value pairs, using methods such as putString() and putInt(). Then, if the system kills your application process and the user navigates back to your activity, the system recreates the activity and passes the Bundle to bothonCreate() and onRestoreInstanceState(). Using either of these methods, you can extract your saved state from the Bundle and restore the activity state. If there is no state information to restore, then the Bundlepassed to you is null (which is the case when the activity is created for the first time).

当这个activity有被系统销毁的趋势时系统会调用该onSaveInstanceState()方法。 系统会将Bundle对象传递到该方法中,你可以将activity的状态信息以键值对的形式保存到Bundle对象中,例如使用putString(),putInt()等数据保存到Bundle中。之后,如果系统杀死了你的应用的进程(这里应该是系统回收了activity吧?)用户又返回到该activity时,系统会重新创建该activity并且将Bundle对象传递到onCreate()和onRestoreInstanceState()中。用这两个中的任何一个方法你都可以从Bundle对象中提取到之前保存的数据并且恢复之前的状态。如果没有要恢复的数据则Bundle为null(这属于activity首次被创建的情况)。

Figure 2. The two ways in which an activity returns to user focus with its state intact: either the activity is destroyed, then recreated and the activity must restore the previously saved state, or the activity is stopped, then resumed and the activity state remains intact.

数字2:activity状态完整的返回到用户焦点(前台,且获取焦点)的两种方式:activity被销毁,然后重新创建并且必须恢复之前保存的数据;或者activity不可见,然后重新获取焦点并且activity状态保存完整。

Note: There's no guarantee that onSaveInstanceState() will be called before your activity is destroyed, because there are cases in which it won't be necessary to save the state (such as when the user leaves your activity using the Back button, because the user is explicitly closing the activity). If the system callsonSaveInstanceState(), it does so before onStop() and possibly before onPause().

提示:并不能保证你的activity被销毁之前onSaveInstanceState()一定会被调用,因为有些情况下没必要保存activity的状态数据(例如当用户按返回按钮离开activity时,因为用户确定关闭了activity)。如果系统需要调用onSaveInstanceState(),则会在onStop()之前调用并且也可能在onPause()之前调用。

However, even if you do nothing and do not implement onSaveInstanceState(), some of the activity state is restored by the Activity class's default implementation of onSaveInstanceState(). Specifically, the default implementation calls the corresponding onSaveInstanceState() method for every View in the layout, which allows each view to provide information about itself that should be saved. Almost every widget in the Android framework implements this method as appropriate, such that any visible changes to the UI are automatically saved and restored when your activity is recreated. For example, the EditText widget saves any text entered by the user and the CheckBox widget saves whether it's checked or not. The only work required by you is to provide a unique ID (with the android:id attribute) for each widget you want to save its state. If a widget does not have an ID, then the system cannot save its state.

然而,即使你什么也不做也不实现onSaveInstanceState()方法,一些activity的状态也会被Activity类默认的onSaveInstanceState()方法保存。需要强调的是,这个默认的手段会为布局中的每一个View对象调用其相应的onSaveInstanceState()方法保存自身的数据。几乎Android框架中的每一个控件都默认实现了该onSaveInstanceState()方法,因此用户界面上任何可见的变化都会被保存并且当activity被重建时也会被恢复。例如,EditText控件会保存用户输入的文本,CheckBox控件会保存是否被选中的状态。你唯一需要做的就是为每一个你想保存其状态的控件指定一个唯一的id(通过android:id的方式)。如果控件没有ID,系统就不能保存它的状态。

Although the default implementation of onSaveInstanceState()saves useful information about your activity's UI, you still might need to override it to save additional information. For example, you might need to save member values that changed during the activity's life (which might correlate to values restored in the UI, but the members that hold those UI values are not restored, by default).

尽管onSaveInstanceState()默认的实现保存了用户界面的有用的信息,但是你仍然可能需要重写该方法去保存更多额外的数据。例如,你可能需要保存那些在activity的整个生命周期中发生变化的成员变量的值(这些值可能需要显示到用户界面,但是默认情况下又不会自动恢复)。

Because the default implementation of onSaveInstanceState() helps save the state of the UI, if you override the method in order to save additional state information, you should always call the superclass implementation of onSaveInstanceState() before doing any work. Likewise, you should also call the superclass implementation of onRestoreInstanceState() if you override it, so the default implementation can restore view states.

因为activity中onSaveInstanceState()方法的默认实现会保存UI中组件的状态信息,但是如果你希望保存更多额外的信息,你应该先调用父类的onSaveInstanceState()方法再执行你自定义的操作。同样,如果你需要重写onRestoreInstanceState()你也应该先调用父类的onRestoreInstanceState()方法,这样父类的方法就可以恢复view组件的状态。

Note: Because onSaveInstanceState() is not guaranteed to be called, you should use it only to record the transient state of the activity (the state of the UI)—you should never use it to store persistent data. Instead, you should use onPause() to store persistent data (such as data that should be saved to a database) when the user leaves the activity.

提示:因为onSaveInstanceState()方法并不一定会执行,所以你应该在该方法中保存activity状态的临时信息(UI状态),而不应该保存持久化的额数据。当用户离开activity时你可以在onPause()中保存持久化的数据(例如需要保存到数据库中的数据等)。

A good way to test your application's ability to restore its state is to simply rotate the device so that the screen orientation changes. When the screen orientation changes, the system destroys and recreates the activity in order to apply alternative resources that might be available for the new screen configuration. For this reason alone, it's very important that your activity completely restores its state when it is recreated, because users regularly rotate the screen while using applications.

通过旋转设备改变屏幕的方向可以很好的测试你的应用的恢复状态的能力。当屏幕的方向发生变化时,为了适应新的屏幕格局系统会销毁并重建activity。因此,当activity重建时完整地恢复之前的状态就非常重要 ,因为用户在使用过程中可能会经常旋转屏幕。

Handling configuration changes

Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language). When such a change occurs, Android recreates the running activity (the system calls onDestroy(), then immediately calls onCreate()). This behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources that you've provided (such as different layouts for different screen orientations and sizes).

一些设备在运行时结构可能会发生变化(例如旋转屏幕,键盘的显示与否以及语言等)。当这种变化发生时Android系统会重新创建activity(系统会先调用onDestroy()紧接着调用onCreate())。依此来帮助你的应用去适应新的屏幕结构。

If you properly design your activity to handle a restart due to a screen orientation change and restore the activity state as described above, your application will be more resilient to other unexpected events in the activity lifecycle.

如果你能像上面那样让你的activity在屏幕方向发生变化时能够重建并且恢复activity的状态,当在activity的生命周期发生其它意外情况时也按照这种方式处理你的应用会更加健壮。

The best way to handle such a restart is to save and restore the state of your activity usingonSaveInstanceState() and onRestoreInstanceState() (or onCreate()), as discussed in the previous section.

处理类似activity重建的问题的最好的方式就是像之前讨论的那样,用onSaveInstanceState()和onRestoreInstanceState()(或onCreate())来保存和恢复activity之前的状态。

For more information about configuration changes that happen at runtime and how you can handle them, read the guide to Handling Runtime Changes.

更多关于运行时布局结构发生变化以及如何去操控他们可以参考"Handling Runtime Changes"相关文档。

Coordinating activities

When one activity starts another, they both experience lifecycle transitions. The first activity pauses and stops (though, it won't stop if it's still visible in the background), while the other activity is created. In case these activities share data saved to disc or elsewhere, it's important to understand that the first activity is not completely stopped before the second one is created. Rather, the process of starting the second one overlaps with the process of stopping the first one.

当一个activity启动另一个activity时,它们都会经历生命周期的转变。当另一个activity被创建时之前的activity会失去焦点并且不可见(当然,如果在该activity在后台时用户仍能看的见该activity将不会被stop)。如果这些activity共享保存在磁盘或其它地方的数据(或者,这些activity共享的数据被保存在磁盘或其它地方,不确定怎么翻译),这时,理解在第二个activity被创建之前,之前的activity并没有被完全终止就非常重要了。相反地,启动第二个activity的进程和终止第一个activity的进程存在重叠的部分。

The order of lifecycle callbacks is well defined, particularly when the two activities are in the same process and one is starting the other. Here's the order of operations that occur when Activity A starts Acivity B:

生命周期的回调方法已经很好的说明,特别是当两个activity处于同一个进程并且其中的一个activity正在启动另一个时。下面是当activity A启动activity B时生命周期回调方法的调用顺序。

  1. Activity A's onPause() method executes.
  2. Activity B's onCreate()onStart(), and onResume() methods execute in sequence. (Activity B now has user focus.)
  3. Then, if Activity A is no longer visible on screen, its onStop() method executes.

This predictable sequence of lifecycle callbacks allows you to manage the transition of information from one activity to another. For example, if you must write to a database when the first activity stops so that the following activity can read it, then you should write to the database during onPause() instead of duringonStop().

通过这种activity生命周期方法的执行顺序你可以很好的管理从一个activity到另一个activity的信息的转化。例如,如果你想在之前的activity停止时向数据库中写入数据,并且后面的activity可以方法这些数据,那么你应该在activity的onPause()中写入数据,而不是在onStop()方法中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值