Android API Guides - Activities

原文地址:http://developer.android.com/guide/components/activities.html

附件是翻译好的 word 文档,很对页面字体特效什么的从word中复制到博客里就花了。。。所以提供下word下载,没事也可以离线下载看看

如果有翻译错误以及错别字,麻烦回复提醒我一下,好人一生平。

另外:安利一个 GitHub 上别人汉化好的 Google Android Training 

            地址是 http://hukai.me/android-training-course-in-chinese/index.html

            这个 GitHub 项目地址是 https://github.com/kesenhoo/android-training-course-in-chinese

---------------------------------------------------------------------------------------------------

Activities

In this document 本文内容

1.    Creating an Activity创建一个 Activity

1.    Implementing a user interface实现一个用户界面

2.    Declaring the activity in themanifest manifest中声明该 activity

2.    Starting an Activity启动一个 activity

1.    Starting an activity for a result启动一个 activity并获得它的执行结果

3.    Shutting Down an Activity关闭一个 activity

4.    Managing the Activity Lifecycle管理 activity的绳命周期

1.    Implementing the lifecyclecallbacks实现绳命周期的回调

2.    Saving activity state保存 activity的状态

3.    Handling configuration changes应对配置的变动

4.    Coordinating activities同时运行的activity

Key classes 关键类

1.    Activity

See also 另请参见

1.    Tasks and Back Stack

An Activity is an applicationcomponent that provides a screen with which users can interact in order to dosomething, 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 windowtypically fills the screen, but may be smaller than the screen and float on topof other windows.

所谓Activity ,就是一个提供屏幕展现形式(screen)的应用程序组件。用户可以通过 Activity 绘制的屏幕来与应用程序交互以便完成自己想要的操作,比如拨打电话,拍照,发送电子邮件或查看地图等等。每个Activity 都会被给与一个窗口来绘制它的用户界面。这个窗口通常是填充满整个屏幕的,但有时候也可能比屏幕小并且浮在其他窗口之上。

An application usually consists of multiple activities that are looselybound to each other. Typically, one activity in an application is specified asthe "main" activity, which is presented to the user when launchingthe application for the first time. Each activity can then start anotheractivity in order to perform different actions. Each time a new activitystarts, the previous activity is stopped, but the system preserves the activityin a stack (the "back stack"). When a new activity starts, it ispushed onto the back stack and takes user focus. The back stack abides to thebasic "last in, first out" stack mechanism, so, when the user is donewith the current activity and presses the Back button, it ispopped from the stack (and destroyed) and the previous activity resumes. (Theback stack is discussed more in the Tasks and Back Stack document.)

应用程序通常包含有多个 Activity 松散地结合在一起。通常情况下,会有一个 Activity 被指定为主(Main)Activity ,当用户第一次启动应用时,主 Activity 就会呈现给用户。在这之后,每个 Activity 都可以启动其他 Activity 来完成不同的操作。每当一个新的 Acitivity 启动之后,之前的 Activity 就会被停止并被系统保存在一个栈中(the “back stack”)。当一个新Activity启动之后,它就会被压入栈中,并获得用户焦点。这个栈遵从“后进先出”的原则,因此当用户完成的在当前Activity中的操作并按下返回按钮时,当前的Activity就会从栈顶被移出(并被销毁)而之前的Activity就会被恢复。(有关栈的更多详情请翻阅《Tasks and Back Stack》一文)

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

当一个Activity因为另一个新Activity启动而停止的时候,状态的改变信息会通过调用它的生命周期方法来通知到它。一个Activity会根据状态的改变—当系统创建、停止、恢复或者销毁它时—而收到好几种生命周期方法的回调,而每次方法的回调也是给开发人员提供了一个时机来执行应对该状态变化的相关操作。举个栗子,当Activity被停止时,你的Activity就应该释放任何大的对象,比如一个网络或者数据库连接。当Activity被恢复的时候,你就可以重新获取必要的资源并继续执行被打断的操作。也正是这些状态的改变构成了整个Activity的生命周期。

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

本文接下来的内容即讨论的如果构建并使用一个 Activity ,这包括一个彻底而全面的、有关Activity的生命周期是如何运转的探讨,而这有助于你正确地应对activity在各种状态之间的转变。

Creating an Activity 创建一个Activity


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

要创建一个 activity ,你就必须要创建一个 Activity 类的子类(或者一个它现有的子类)。在你的子类中,你需要实现回调方法以便当activity的状态改变时供系统来调用,比如当activity被创建、停止、恢复会或者销毁时。而在这其中有两个至关重要的回调方法:

onCreate()

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

你必须实现这个方法。在你的activity被创建时,这个方法就会被系统调用。在你具体的实现过程中,你应该初始化那些必要的组件,而重中之重是,你必须调用 setContentView() 方法来设置该activity 对应的用户界面的布局结构。

onPause()

The system calls this method as the first indication that the user isleaving your activity (though it does not always mean the activity is beingdestroyed). This is usually whereyou should commit any changes that should be persisted beyond the current usersession (because the user might not come back).

系统调用此方法即为用户将要离开你的 activity 的第一个迹象(不过这并不总意味着这个 activity 将会被销毁)。因为用户离开后也许不会再返回到当前的activity,所以这个方法也通常是你提交更改的地方,提交那些即使当前的用户会话(session)结束之后也应该被永久性保存的更改。

There are several other lifecycle callback methods that you should use inorder to provide a fluid user experience between activities and handleunexpected interuptions that cause your activity to be stopped and evendestroyed. All of the lifecycle callback methods are discussed later, in thesection about Managing the Activity Lifecycle.

还有一些其他生命周期回调方法来供你使用以便能够提供一个能在各个activity之间流畅切换的用户体验以及应对那些导致你activity停止甚至销毁的意外中断。所有的生命周期回调方法在后续都会被讨论,详情请参阅 Managing the Activity Lifecycle章节。

Implementing a user interface实现一个用户界面

The user interface for an activity is provided by a hierarchy ofviews—objects derived from the View class. Each view controls a particularrectangular space within the activity's window and can respond to userinteraction. For example, a view might be a button that initiates an actionwhen the user touches it.

一个activity的用户界面是由多个视图组件共同构成的一个层次结构(a hierarchy of views of views)来提供的,每个视图都是继承自 View类的子类。每个视图组件都控制这个 activity 窗口的一部分特定的矩形空间,并且能够与用户进行交互。举个栗子,一个 view 可能就是一个按钮,当用户触碰它时就会执行相应的操作。

Android provides a number of ready-made views that you can use to designand 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 itschild views, such as a linear layout, a grid layout, or relative layout. Youcan also subclass the View and ViewGroupclasses (or existing subclasses) to create yourown widgets and layouts and apply them to your activity layout.

Android 提供了许多现成的视图组件供开发者使用来设计和组织自己的界面布局。视图组件中有一部分被称之为“Widgets”,指的就是那些为屏幕提供视觉效果(并且能够与之交互)的元素,比如说一个按钮,一个文本输入框,一个复选框或者一个图片等。而还有一些继承自 ViewGroup 类的、被称为“Layouts”的视图组件则是用来为它的子视图组件提供一个独一无二的布局模型,比如线性布局,网状布局或者相对布局。你也可以自行继承View 类或者 ViewGroup 类来创建自己的 widgets 或者 layouts (或者使用现成的子类),并使用它们来设计你的activity布局。

The most common way to define a layout usingviews is with an XML layout file saved in your application resources. This way, you can maintain the design of youruser interface separately from the source code that defines the activity'sbehavior. 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 viewhierarchy by inserting new Views into a ViewGroup, then use that layout by passing the root ViewGroup tosetContentView().

设计一个布局结构的最常见的方法是使用一个保存在你应用程序资源中里的XML布局文件。使用这种方法就可以将你的界面设计与定义了 activity 行为特性的源代码分开存储。你可以将布局文件的资源 ID 传给 setContentView() 方法来将这个布局文件指定为你activity的UI布局形式。当然,你也可以在代码中设计你的界面展现形式,具体做法是,在你的activity代码中新建视图组件,然后将新的视图组件添加进视图组(ViewGroup)中来构成一个视图的层次结构,然后将它传递给根ViewGroup的setContentView()方法。

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

有关创建用户界面的更多信息,请参阅《User Interface》一文。

Declaring the activity in the manifest在 manifest 中声明该 activity

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

你必须在 manifest 文件中声明你的 activity ,这样它才能被系统所调用。所谓声明,即在你的 manifest 文件的 <application> 节点下新增一个 <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 theactivity, or a theme to style the activity's UI. The android:name attribute is the only requiredattribute—it specifies the class name of the activity. Once you publish yourapplication, you should not change this name, because if you do, you mightbreak some functionality, such as application shortcuts (read the blogpost, Things That Cannot Change).

在<activity>节点中有许多属性可以设置,这些属性可以设置 activity 的标签、图标或者 activity 的 UI 风格等。而在这些属性当中,只有 android:name 属性是必须的,它定义了被声明的 activity 所对应的java 类。而一旦你发布了你的应用程序之后,你就不应该再改变这个名字,因为一旦你改了,那就可能导致某些功能异常,比如说应用程序快捷方式。(更多信息,请参阅《Things That CannotChange(不能改变的东西)》这篇博文)

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

如要了解更多关于如何在manifest中声明activity的详细信息,请点击 <activity> 指向的超链接页面。

Using intent filters使用 Intent 过滤器

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

一个 <activity> 也可以使用 <intent-filter> 标签来指定多个 intent 过滤器,以便声明其他应用程序组件该如何调用它。

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

当时使用 Android SDK tools 来新建一个应用程序的时候,系统为你创建的主activity (the stub activity)默认就含有一个 intent 过滤器(如下图),这个intent 过滤器定义了该 activity 能够相应“launcher”类型的“main”动作:

<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 activityshould be listed in the system's application launcher (to allow users to launchthis activity).

这个<action>元素指定了这个activity是这个应用程序的“主”入口而这个<category>指定了这个activity应该被列入系统的应用程序启动器中(以允许用户来启动这个activity)。

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

如果你希望你的应用程序是“自给自足”、不可以被其他应用程序所激活的话,你就只需要一个之前的示例代码中的那个intent 过滤器,只包含了“main”动作和“launcher”类型。如果你不希望你的activity 供其他应用程序所调用,那就不应该给它指定intent 过滤器,而你自己则可以直接使用明确的intent来调用它(接下来的章节就会讨论这个)。

However, if you want your activity to respond to implicit intents that aredelivered from other applications (and your own), then you must defineadditional intent filters for your activity. For each type of intent to whichyou 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 typeof intent to which your activity can respond.

但如果你希望你的activity能够响应其他应用程序(或者从你自己那里)传来的隐式 intent 的话,你就必须要为你的 activity 新添一个 intent 过滤器。而对用于每一种你想要响应的 intent 类型,你都必须要在 <intent-filter> 中添加一个必选的<action>子节点以及可选的<category>、<data>子节点。而这些子节点就确定了你的activity能够响应什么样的intent。

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

更多有关于你的activity如何响应intent的信息,请参阅 Intents and Intent Filters 一文

Starting an Activity 启动一个 activity


You can start another activity by calling startActivity(), passing it an Intent that describes the activity you want tostart. The intent specifies either the exact activity you want to start ordescribes the type of action you want to perform (and the system selects theappropriate 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 thatis started.

你可以定义一个描述了你想要启动哪个activity的Intent,然后将它传入 startActivity() 方法来启动另一个 activity。这个被定义的 intent 既可以指明你想要启动哪个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 thatexplicitly defines the activity you want to start, using the class name. Forexample, here's how one activity starts another activity named SignInActivity:

当你不需要跨应用地启动activity时,通常情况下你仅仅是简单地启动一个已知的activity,而它的类名也是你自己定义的,所以你可以直接根据这个类名来定义你的intent,明确地指出你需要启动哪一个activity:

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

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

但是,你的应用程序也可能想要使用一些来自于你activity的数据来执行一些诸如发送电子邮件,写短信或者状态更新的操作。在这种情况下,你的应用程序可能并没有执行这些操作的activity,所以作为替代的,你就可以利用设备上的其他应用程序来为你执行这些操作。而这才是Android 的 intent 机制真正展现其价值的地方——你可以新建一个intent来描述你所需要执行的操作,然后系统就会从另一个应用程序中启动合适的activity来帮你完成这个操作。如果有多个activity都适用于你的intent那么系统就会让用户来选择。比如当你想要用户来发送一封电子邮件时,你就可以这么来定义你的intent:

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

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

这个名为 EXTRA_EMAIL 的附加信息是一个字符串数组,它包含了邮件的接受人地址。当一个电子邮件应用响应了这个intent之后,它就会读取这个附加信息中的字符串数组,然后将读取到的收件人信息自动填入到写邮件界面的“发送给”那一栏中去。当电子邮件应用被启动然后用户完成了相关的操作,那么你的activity就会恢复运行。

Starting an activity for a result启动一个 activity 并获得它的执行结果

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

有时,你或许希望从你启动的activity中获取操作的执行结果。在这时候你就应该调用 startActivityForResult() 方法来替代 startActivity() 方法。而为了接收从被调用的activity中传回的结果,你就需要实现 onActivityResult() 方法。当被调用的activity结束之后,它就会通过intent的形式返回一个结果到你的 onActivityResult() 方法。

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

举个栗子,或许你可能需要用户来选中一个联系人然后你的activity就可以根据这个联系人信息来执行后续的操作。下面的代码就展示了你该如何创建这个intent并获取它的返回结果:

private void pickContact(){
    // Createan intent to "pick" a contact, as defined by the content provider URI创建一个选择联系人的 intent, 就像content provider所定义的那样
    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 therequest went well (OK) and the request was PICK_CONTACT_REQUEST如果请求顺利执行,并且请求代码是PICK_CONTACT_REQUEST
    if (resultCode==Activity.RESULT_OK&&requestCode== PICK_CONTACT_REQUEST){
        // Perform a query to the contact's content provider for the contact'sname向联系人 contentprovider中执行一个查询姓名的查询操作
        Cursor cursor = getContentResolver().query(data.getData(),
        new String[]{Contacts.DISPLAY_NAME},null,null,null);
        if (cursor.moveToFirst()){// True if the cursor is not empty当查询结果不为空时返回 true
            int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
            String name = cursor.getString(columnIndex);
            // Do something with the selected contact'sname...根据这个联系人的姓名来执行下一步的操作
        }
    }
}

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

这段示例代码展示了一个应该用在 onActivityResult() 方法中以便处理activity的返回结果的基本逻辑流程。第一个条件检查判断了这个请求是否执行顺利,如果是的话,那么resultCode 就等于 RESULT_OK同时也清楚了这个结果究竟是对应了哪个请求——在这种情况话 requestCode 就与传入 startActivityForResult() 方法的第二个参数一致。在上述示例代码中,代码对activity返回的结果进行的处理即对返回的intent对象(也就是 data 参数)进行了一次查询。

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

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

而这个查询的内部流程是,一个 ContentResolver 对一个 content provider 执行了一次查询,然后返回了一个 Cursor,而通过这个 Cursor 即可读取被查询到的数据。更多相关信息,请参阅《Content Providers》一文。有关更多运行intent的介绍,请参阅《Intents and Intent Filters》一文。

Shutting Down an Activity关闭一个 activity


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

你可以通过调用一个activity的finish()方法来关闭它。你也可以通过调用finishActivity()方法来关闭一个你之前启动的独立的activity。

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

注意:绝大多数情况下,你都不应该手动地调用这些方法来结束你的activity。在接下来有关activity的生命周期的讨论中你会知道,Android 系统会为你管理 activity,因此你并不需要手动地来关闭你的activity。而调用上述两个方法会不可逆地影响到预期的用户体验,这两个方法只由在你绝不希望用户再返回到这个activity 实例时才可以被调用。

Managing the Activity Lifecycle 管理 activity 的绳命周期


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

通过实现回调函数来管理activity的生命周期,这一做法有利于开发出一个健壮的、易于扩展的应用程序。一个 activity 实例的生命周期直接影响到它与其他activity之间的关联、它的工作任务以及后台堆栈。

An activity can exist in essentially threestates:

本质上来说当一个activity处于下面三种状态之一时,它才可以被认为是存在的。

Resumed 继续状态

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

当前的activity处于屏幕的前台,并且拥有用户焦点。(这个状态有时也被称之为“运行状态”)。

Paused 暂停状态

Another activity is inthe foreground and has focus, but this one is still visible. That is, anotheractivity is visible on top of this one and that activity is partiallytransparent or doesn't cover the entire screen. A paused activity is completelyalive (the Activity object is retained in memory, it maintainsall 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之上并且是半透明的或者并没有占满真个屏幕。一个被暂停的activity完全是处于活动状态的(这个 activity 对象依旧保存在内存中,它依然维持着所有的状态和成员信息,并且依然附着在窗口管理器上),但是在极端的缺乏内存的情况下,它依旧有可能被系统销毁以释放资源。

Stopped 停止状态

The activity iscompletely 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 maintainsall state and member information, but is not attached to thewindow manager). However, it is no longer visible to the user and it can bekilled by the system when memory is needed elsewhere.

If an activity is pausedor 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 becreated all over.

当activity完全被其他activity遮盖住时即处于停止状态(activity现在处于“后台”)。一个停止状态的activity依旧是处于活动状态的(依旧被保存在内存中,依旧维持着所有的状态和成员信息,但是已经脱离窗口管理器了),但对用户而言已经是不可见的了并且只要其他地方需要内存,它就会被杀死。

当一个activity处于暂停或者停止状态时,系统可能通知它结束(调用它的finish()方法)或者直接杀掉它的进程来从内存中终止它。当这个activity被再次打开时(在被结束或者被杀死之后),它必须被重新创建。

 

Implementing the lifecycle callbacks 实现绳命周期的回调

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

当activity在上述不同的状态之间来回切换时,它会被系统通知,系统通过调用它的各种回调函数来通知它要进行状态切换了。所有的这些回调函数都是钩子(hook,钩子函数?),你可以重写它们以便在状态改变的同时来做你需要做的工作。接下来的代码列举了所有的生命周期方法。

public classExampleActivityextendsActivity{
    @Override
    public voidonCreate(BundlesavedInstanceState){
        super.onCreate(savedInstanceState);
        // The activity is being created. activity实例被创建
    }
    @Override
    protected voidonStart(){
        super.onStart();
        // The activity is about to become visible. activity即将被呈现
    }
    @Override
    protected voidonResume(){
        super.onResume();
        // The activity has become visible (it is now"resumed"). activity已经被呈现(它现在是“继续状态”)
    }
    @Override
    protected voidonPause(){
        super.onPause();
        // Another activity is taking focus (thisactivity is about to be "paused").另一个 activity获得了焦点(当前activity即将被暂停
    }
    @Override
    protected voidonStop(){
        super.onStop();
        // The activity is no longer visible (it is now"stopped") activity将不再可见(它现在是停止状态
    }
    @Override
    protected voidonDestroy(){
        super.onDestroy();
        // The activity is about to be destroyed. activity 即将被销毁
    }
}

Note: Your implementation of these lifecyclemethods 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 activitylifecycle:

所有的这些方法定义了一个activity的整个生命周期。通过实现这些方法,你就可以监听activity生命周期中的三个子循环:

l   The entire lifetime of anactivity 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 threadrunning in the background to download data from the network, it might createthat thread in onCreate() and then stop the thread inonDestroy().

l   一个activity的整个生命周期起于onCreate()方法而止于onDestroy()方法。你的activity应该在onCreate()方法中执行“全局”状态的初始化工作(比如定义布局),并且在onDestroy()方法中释放所有被你占用的资源。比如,假使你的activity有一个运行在后台的线程正在从网络中下载资源,那么这个activity可能在onCreate()方法中创建这个线程并随后在onDestory()方法中停止该线程。

l   The visible lifetime of anactivity happens between the call to onStart() and the call to onStop(). During this time, the user can see theactivity on-screen and interact with it. For example, onStop() is called when a new activity starts andthis one is no longer visible. Between these two methods, you can maintainresources that are needed to show the activity to the user. For example, youcan register a BroadcastReceiver inonStart() to monitor changes that impact your UI,and unregister it in onStop() when the user can no longer see what youare displaying. The system might call onStart() and onStop() multiple times during the entire lifetimeof the activity, as the activity alternates between being visible and hidden tothe user.

l  在一个activity的整个生命周期中,仅当调用onStart()开始,直到调用onStop()方法之前的这段时间才是可见的。在这时,用户能够看到这个activity 并能够与之交互。举个栗子,当一个新的activity启动而当前这个activity不再需要被呈现的时候,onStop()方法就会被调用。在这两个方法之间,你可以维护那些你需要用来将这个activity呈现给用户的相关资源。举个栗子,你可以在onStart()方法中注册一个 BroadcastReceiver 来监听那些影响到你UI的变化信息,随后在onStop()方法中当用户不再需要看到你所呈现的东西时就注销它。在activity的整个生命周期中,因为activity可能会在可见与不可见的状态之间来回切换,所以系统亦可能会多次调用onStart()方法和onStop()方法。

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

l  在一个activity的整个生命周期中,仅当调用onResume()开始,直到调用onPause()方法之前的这段时期,该activity才处于前台。在这段周期中,屏幕中的该activity处于其他activity之上,并持有用户的输入焦点。一个activity会频繁地在前后台之间进行状态切换——举个栗子,当设备即将休眠或者当一个对话框出现的时候,onPause()方法就会被调用。也因为这个状态切换会很频繁,所以在这两个方法之中的代码应该相对地轻量化一些,以避免降低切换状态的速度而导致用户等待。

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

图一展现了一些生命循环周期以及状态之间的改变路线。矩形代表了那些你可以实现的、当activity在状态之间切换时用来执行相关操作的方法。

Figure 1. The activity lifecycle.

图1.Activity 生命周期

但其实我更喜欢下面出自http://developer.android.com/training/basics/activity-lifecycle/index.html的4张图:

Figure 1. Asimplified illustration of the Activity lifecycle, expressed as a step pyramid.This shows how, for every callback used to take the activity a step toward theResumed state at the top, there's a callback method that takes the activity astep down. The activity can also return to the resumed state from the Pausedand Stopped state.

图1. 一个将 activity生命周期画成阶梯形的金字塔的简图。从该图就可以看出,每个回调函数是如何被依次调用而将activity一步步地带到最顶端的继续状态的,而又是怎么一步步地调用回调函数从金字塔的顶端往下走的。另外也可以看出处于暂停状态和停止状态的activity是可以返回到继续状态的。

Figure 2. Another illustration ofthe activity lifecycle structure with an emphasis on the three main callbacksthat the system calls in sequence when creating a new instance of the activity: onCreate()onStart(), and onResume(). Once thissequence of callbacks complete, the activity reaches the Resumed state whereusers can interact with the activity until they switch to a different activity.

图2.另外一副简图,着重显示了创建一个新的activity实例时系统所调用的三个主要的回调函数:onCreate(),onStart()以及onResume()。一旦这三个回调函数依次执行完毕后,这个activity就会处于继续状态,用户就可以与之进行交互,直至它被切换到其他状态之前。

Figure 1. When a semi-transparentactivity obscures your activity, the system calls onPause() and the activity waitsin the Paused state (1). If the user returns to the activity while it's stillpaused, the system calls onResume() (2).

图1.当一个半透明的activity 覆盖在你的activity上,那么系统就会调用onPause()方法然后activity就会在暂停状态(①)中等待。如果当它处于暂停状态时用户要返回到这个activity,那么系统就会调用onResume()方法(②)。

Figure 1. When the user leavesyour activity, the system calls onStop() to stop the activity(1). If the user returns while the activity is stopped, the system calls onRestart() (2), quickly followedby onStart() (3) and onResume() (4). Notice that nomatter what scenario causes the activity to stop, the system always calls onPause() before callingonStop().

图1.当一个半透明的activity 覆盖在你的activity上,那么系统就会调用onPause()方法然后activity就会在暂停状态(①)中等待。如果当它处于暂停状态时用户要返回到这个activity,那么系统就会调用onResume()方法(②)。

 

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

下面的表1也以列表的形式列举出了所有的生命周期回调函数,表1详细描述了每一个回调方法,并且阐述了各个方法在activity的整个生命周期过程中的定位,包括系统在这些回调方法完成之后时候会杀死该activity。

Table 1. A summary of the activity lifecycle'scallback methods. 表1. Activity的生命周期回调方法的摘要

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

该方法在activity第一次被创建的时候被调用。该方法也是你执行所有的常规静态设置操作的地方——比如创建 View,将数据绑定到list中等等。如果先前的状态数据有被保存的话,这个方法会被传入一个含有该activity先前的状态数据的 Bundle 对象(详情请看稍后的“Saving Activity State”部分)。

Always followed by onStart().

该方法的后续生命周期回调方法为onStart()方法。

No

onStart()

    

onRestart()

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

Always followed by onStart().

仅当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被呈现给用户之前被调用。

如果activity被切换成到前台则后期的生命周期回调方法为onResume(),反之,则调用onStop()。

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开始与用户进行交互之前被调用。此时该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.

系统在即将恢复另一个activity时会调用该方法。这个方法通常被用来执行一些诸如,提交一些尚未保存的变化到持久化储存区中(persistent data,能简单地理解成诸如硬盘之类么- -),关掉动画或者类似的会消耗CPU资源的东西,等操作。不管这个方法执行什么操作都应该非常迅速地完成,因为后续的activity是不会等到这个方法执行完毕之后才恢复的。

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

如果该activity接下来返回到前台那么后续的生命周期方法为onResume()方法,如果它之后不需要再被呈现给用户,那么后续方法则为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.

当activity即将被销毁或者另一个activity已经恢复并覆盖在它之上运行时,那么系统就会认为这个activity不再需要被呈现给用户,就会调用该方法。

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

如果该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被销毁之前被调用。该方法是activity能够接收到的最后的方法。它仅当这个activity即将结束的时候(某人调用了它的finish()方法),或者系统临时地销毁了这个activity实例来释放空间的时候被调用。你可以通过调用 isFinishing() 方法来区分这两种情形。

Yes

nothing

The column labeled "Killable after?" indicates whether or notthe system can kill the process hosting the activity at any time afterthe 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 theactivity is created, onPause() is the last method that's guaranteed to becalled before the process can be killed—if the system mustrecover memory in an emergency, then onStop() and onDestroy() might not be called. Therefore, you shoulduse onPause() to write crucial persistent data (such asuser edits) to storage. However, you should be selective about what informationmust be retained during onPause(), because any blocking procedures in this methodblock the transition to the next activity and slow the user experience.

“Killable after(在这之后可以被杀死)?”这列表示在该方法返回之后系统是否随时都可以在没有执行任何该activity的其他代码的情况下杀死持有该activity的进程。有三个方法标注的是“Yes(可以)”:(onPause(), onStop()和onDestroy())。因为onPause()是上述三个方法中的第一个,所以,一旦activity被创建之后,如果系统在紧急情况下需要释放资源,那么在进程被杀死之前,onPause()方法是肯定能被执行的最后一个方法。而onStop()和onDestroy()方法可能还没被调用,进程就直接被杀了。因此,你应该使用onPause()方法来将重要的持久性数据(比如用户的编辑内容)写到存储设备上。但是在onPause()方法中,你也应该有选择性地仅保留那些必须被保留的信息,因为如果这个方法的执行过程中有任何的阻塞现象也会导致切换到下一个activity的过程阻塞,而导致用户觉得卡顿。

Methods that are marked "No" in the Killable columnprotect the process hosting the activity from being killed from the moment theyare called. Thus, an activity is killable from the time onPause() returns to the timeonResume() is called. It will not again be killableuntil onPause() is again called and returns.

在“Killable”列中被标记为“否(No)”的方法表示在这些方法被调用之后,系统被保护这个activity实例不被杀死。因此,一个activity从onPause()方法返回之后到onResume()方法被调用之时的这段时间里是可被杀的。而当onResume()方法被调用之后直至onPause()方法被再次调用和返回之前,该activity都不会再次处于可被杀状态。

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

注意:即使一个activity在表1中没有被技术性地标记为“可被杀”也还是有可能被系统杀死,虽然可能性很小。这种情况只会在系统极度缺乏资源的极端条件下发生。相关内容在《Processes and Threading》一文中有更详尽的描述。

Saving activity state 保存 activity 的状态

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

《Managing the Activity Lifecycle》一节简单说明了,当一个activity被暂停或者被停止的时候,它的状态信息会被保留。这是因为当一个activity被暂停或者被停止的时候,它的实例对象还是被保留在内存中,所有有关它的成员或者当前状态的信息都依然是存活的。因此,在该activity中用户所做的改动都将被保存,并且当activity返回到前台的时候(当它“恢复”的时候),这些改动依然都在。

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

但当系统为了释放内存而销毁一个activity时,一旦这个activity被销毁之后,系统就不能够轻松地将它完全恢复到之前的状态。如果用户返回到这个activity而系统又刚好在这之前将这个activity强制销毁了,那么系统必须要重新创建这个activity对象。然而,对于用户而言,用户并不知道系统已经销毁过并重建了这个activity,因此,用户肯定希望activity还是之前的状态。所以,你必须要确保重要的信息会在onSateInstanceState()方法中被保存,这个方法是一个额外的回调函数,它允许你保存当前activity的状态信息。

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

系统在将activity标记成易于被销毁时会调用onSaveInstanceState()方法。系统会传递给这个方法一个Bundle对象,你可以使用putString()和putInt()等方法来将状态信息以键值对的形式保存到Bundle中。在这之后如果系统杀死了你应用程序的进程并且用户又要返回到你的activity中时,系统就会重建activity并将保存好的Bundle传递给onCreate()方法和onRestoreInstanceState()方法,在这两个方法中随便哪一个都可以提取Bundle中的信息然后恢复activity的状态。如果什么需要恢复的,那么传递给你的Bundle对象就是空的(当activity第一次被创建的时候就是这种情况)。

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

图2. 当一个activity状态完好无损地重新获得用户焦点的两种途径:当activity被销毁后,重新创建该activity并恢复到之前保存的状态;activity停止了,继续运行它,而它的状态依然完整。

但其实我更喜欢下面出自http://developer.android.com/training/basics/activity-lifecycle/index.html的1张图:

Figure 2. As the system begins tostop your activity, it calls onSaveInstanceState() (1) so you can specifyadditional state data you'd like to save in case the Activity instance must berecreated. If the activity is destroyed and the same instance must berecreated, the system passes the state data defined at (1) to both the onCreate() method (2) and theonRestoreInstanceState() method (3).

图2.当系统开始停止你的activity时,它会调用onSaveInstanceState()(①)方法,所以你可以在这里指明你需要保存的状态数据以防这个activity实例待会又要重新被创建。如果这个activity被销毁然后又必须要重建的时候,系统就会将在步骤①中保存的状态数据传递给onCreate()(②)方法和onRestoreInstanceState()(③)方法中。

Note: There's no guarantee that onSaveInstanceState() will be called before your activity isdestroyed, because there are cases in which it won't be necessary to save thestate (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().

注意: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 bythe Activity class's default implementation of onSaveInstanceState(). Specifically, the default implementation callsthe corresponding onSaveInstanceState() method for every View in the layout, which allows each view toprovide information about itself that should be saved. Almost every widget inthe Android framework implements this method as appropriate, such that anyvisible changes to the UI are automatically saved and restored when youractivity is recreated. For example, the EditText widget saves any text entered by the userand 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 tosave its state. If a widget does not have an ID, then the system cannot saveits state.

但即使你啥都没做也没有实现onSaveInstanceState(), activity状态的一些信息也会被Activity类的onSaveInstanceState()方法的默认实现所保存。默认的实现过程是调用布局中每一个View实例的onSaveInstanceState()方法,而View的onSaveInstanceState()方法的作用是提供那些它自己的需要被保存的信息。Android 框架中几乎每一中小部件(widget)都实现了相应的onSaveInstanceState()方法,因此UI中所有的可见的变化都会被自动保存并随后在重建的时候被恢复。举个栗子,EditText (输入框)小部件保存了所有用户输入的文本而CheckBox(复选框)小部件保存了它是否被选中的信息。而开发人员在使用这一特性时,所需要做的唯一操作则是给每个需要保存状态信息的小部件都设置一个唯一的ID(使用 android:id 属性)。如果小部件不含有ID的话,那系统就无法保存它的状态。

You can also explicitly stop a view in your layout from saving its stateby setting the android:saveEnabledattribute to "false" or by calling thesetSaveEnabled() method. Usually, you should not disable this, but youmight if you want to restore the state of the activity UI differently.

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

你也可以显示地将 android:saveEnabled 属性设置成“false”或者调用 setSaveEnabled() 方法来禁用掉这个功能。通常情况下,你不需要禁用它,但你可能会在要将activity的UI恢复成不同的样子的时候会想要禁用它。

尽管onSaveInstanceState()方法的默认实现已经保存你UI中的那些有用的信息,但你或许还是会需要重写它来保存一些其他信息。比如,你可能需要保存那些在生命周期中发生的成员变量(这些成员变量可能会关联到恢复UI所需要的数据,但是默认情况下,这些成员变量又是不能自动保存的)。

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

因为onSaveInstanceState()方法的默认实现已经帮你保存了UI的状态,所以如果你要重写这个方法来保存额外的信息的话,你应该总是在执行自己的操作之前先调用父类的实现。同样的,你在重写onRestoreInstanceState()时也应该先调用父类的实现。这样默认的实现才能起作用帮你自动恢复UI。

Note: Because onSaveInstanceState() is not guaranteed to be called, you shoulduse it only to record the transient state of the activity (the state of theUI)—you should never use it to store persistent data. Instead, you shoulduse onPause() to store persistent data (such as datathat 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 tosimply rotate the device so that the screen orientation changes. When thescreen orientation changes, the system destroys and recreates the activity inorder to apply alternative resources that might be available for the new screenconfiguration. For this reason alone, it's very important that your activitycompletely restores its state when it is recreated, because users regularlyrotate the screen while using applications.

一个测试你的应用程序是否能够很好的保存它的状态的好方法是旋转设备来改变屏幕方向。当设备的屏幕方向改变后,系统就会销毁并重建activity以便更适合新的屏幕方向的布局资源文件。也正因此,当你的activity被重建时,是否能够完美地恢复到它先前的状态是很重要的,因为用户在使用应用程序的过程中经常会旋转屏幕。

Handling configuration changes 应对配置的变动

Some device configurations can change during runtime (such as screenorientation, 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 yourapplication adapt to new configurations by automatically reloading yourapplication with alternative resources that you've provided (such as differentlayouts for different screen orientations and sizes).

一些设备配置可能会在运行过程中发生改变(比如屏幕方向,键盘可用性,以及语言)。当一个变动发生后,Android会重建当前正在运行的activity(系统调用onDestroy()方法,然后立即调用onCreate()方法)。这一特性是被设计用来帮助你的应用程序调用预设好的可替换资源,自动地重新装载你的应用程序,以适应新的设备配置。

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

如果你正确地设计了你的activity来应对一个因为屏幕方向改变而导致的重启并如上所述地恢复了activity的状态,那么你的应用程序在遇到activity生命周期中的其他不可预知的事情时也有了更大的弹性。

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

最好的处理重启类似的重启的方法是使用onSaveInstanceState()方法来保存你activity的状态信息,并使用onRestoreInstanceState()方法(或者onCreate()方法)来恢复状态,就像先前所述的那样。

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

更多有关运行时可能发生的改变以及如何应对这些改变,请阅读《Handing Runtime Changes》这篇指导文章。

Coordinating activities 同时运行的activity

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

当一个activity启动另一个时,它们两都经历了生命周期的状态转换。第一个activity暂停并停止(当然,如果它还是可见的话就不会停止),而另一个activity则会被创建。一旦这些activity共享保存在光盘或者类似的其他地方的数据,那么理解这一点是很重要的,即在第二个activity被创建好之前第一个activity并没有完全被停止。更确切地说应该是启动第二个activity的进程和停止第一个activity的进程是同时运行的。

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

生命周期回调函数的调用次序是明确定义好的,尤其是当两个activity都处于同一个进程中,而一个正在启动另一个时。当Activity A启动B时,发生的操作顺序是这样的:

1.      Activity A's onPause() method executes. 执行Activity A 的 onPause() 方法

2.      Activity B's onCreate()onStart(), and onResume() methods execute in sequence. (Activity Bnow has user focus.) 依次执行B的onCreate(),onStart()和onResume()方法(B现在获得了用户焦点)。

3.      Then, if Activity A is no longer visible on screen, its onStop() method executes. 随后,如果A在屏幕上不再可见则调用它的onStop()方法。

This predictable sequence of lifecycle callbacks allows you to manage thetransition of information from one activity to another. For example, if youmust write to a database when the first activity stops so that the followingactivity can read it, then you should write to the database during onPause() instead of during onStop().
理解这个可预知的生命周期回调方法的调用次序,有助于你正确地将数据从第一个activity传递到随后的那个activity中。举个栗子,如果你必须在第一个activity停止时将有关数据写入到数据库以便下一个activity读取它,那么你就应该在onPause()方法中执行写入操作而不是在onStop()方法中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
疫情居家办公系统管理系统按照操作主体分为管理员和用户。管理员的功能包括办公设备管理、部门信息管理、字典管理、公告信息管理、请假信息管理、签到信息管理、留言管理、外出报备管理、薪资管理、用户管理、公司资料管理、管理员管理。用户的功能等。该系统采用了MySQL数据库,Java语言,Spring Boot框架等技术进行编程实现。 疫情居家办公系统管理系统可以提高疫情居家办公系统信息管理问题的解决效率,优化疫情居家办公系统信息处理流程,保证疫情居家办公系统信息数据的安全,它是一个非常可靠,非常安全的应用程序。 管理员权限操作的功能包括管理公告,管理疫情居家办公系统信息,包括外出报备管理,培训管理,签到管理,薪资管理等,可以管理公告。 外出报备管理界面,管理员在外出报备管理界面中可以对界面中显示,可以对外出报备信息的外出报备状态进行查看,可以添加新的外出报备信息等。签到管理界面,管理员在签到管理界面中查看签到种类信息,签到描述信息,新增签到信息等。公告管理界面,管理员在公告管理界面中新增公告,可以删除公告。公告类型管理界面,管理员在公告类型管理界面查看公告的工作状态,可以对公告的数据进行导出,可以添加新公告的信息,可以编辑公告信息,删除公告信息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值