当前位置: 代码迷 >> Android >> android activity开发文档翻译 - 二 - 生命周期篇
  详细解决方案

android activity开发文档翻译 - 二 - 生命周期篇

热度:102   发布时间:2016-05-01 15:06:16.0
android activity开发文档翻译 - 2 - 生命周期篇

由于本人英文能力实在有限,不足之初敬请谅解

本博客只要没有注明“转”,那么均为原创,转贴请注明本博客链接


android activity开发文档翻译 - 1 - 基础篇

android activity开发文档翻译 - 2 - 生命周期篇


本系列并没有对原文100%翻译,也没有100%的贴出原文


导读

下面的内容至关重要


1.介绍生命周期函数及其调用顺序

2.生命周期的意外:比如系统恢复内存时

3.onSaveInstanceState()和onRestoreInstanceState()调用时机和如何使用

4.配置的改变(比如屏幕方向,键盘有效性和语言)

5.两个activity转换时的生命周期回调函数的执行顺序



Managing the Activity Lifecycle

管理Activity生命周期

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、它的task和back stack直接所影响。


An activity can exist in essentially three states:

一个activity本质上可以存在3中状态


Resumed

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

activity在屏幕的前台且拥有用户焦点(这个状态有时也指“运行中”)


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之上是可见的,并且它是部分透明的或者没有覆盖整个屏幕

一个暂停的activity是完全活着的(Activity对象在内存中保留,它保持着所有的状态和成员信息,并且依然附属在window manager),但是可能会被系统在内存极低的情况下杀死。


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.

If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling its finish() method), or simply killing its process. 

When the activity is opened again (after being finished or killed), it must be created all over.

这个activity完全被另一个activity遮盖(这个activity现在处于后台中)

一个停止的activity也仍然是活着的(Activity对象在内存中保留,它保持着所有的状态和成员信息,并且依然附属在window manager)。

然而,它对用户不再可见,并且在需要内存的其他地方可以被系统杀死

如果一个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状态改变时你可以覆盖来做恰当的工作的钩子。

下面的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生命周期中监听3个嵌套循环。



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 in onDestroy().

activity的整个生命期间是介于调用onCreate()和调用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 a BroadcastReceiver 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.

activity的可见生命周期是介于调用onStart()和调用onStop()之间的。

在这段时间期间,用户可以在屏幕看见activity并与之交互。

例如,当一个新的activity启动时此activity的onStop()被调用,并且它不再可见。

在这两个方法之间,你可以维持需要展示给用户的资源。

例如,你可以在onStart()中注册一个BroadcastReceiver来监视影响你UI的改变,当用户不再能看到你显示的内容时,在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.

activity的前台生命是在onResume()与onPause()之间。

在这段时间期间,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在状态间转换的时候你可以实现的回调函数来执行操作。



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.

相同的生命周期回调函数在表格中列出。描述每个回调函数的更多细节和确定每一个在activity总的生命周期的位置,包括系统能否在回调函数完成之后杀死activity。


方法描述之后是否可被杀死下一个
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第一次建立时调用

你应该在这做所有的你普通的静态设置 - 建立view,绑定list数据等等

这个方法传递一个包含此activity之前状态(如果这个状态被捕获了)的Bundle。

后面总是跟着onStart()

noonStart()
onRestart()

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

Always followed by onStart()


在activity停止后开始之前调用

后面总是跟着onStart()

noonStart()
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来到前台,后面跟着onResmue(),否则如果隐藏,后面跟着onStop()

noonResume()或者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的stack顶部,带着用户的输入进入。

后面总是跟着onPause()

noonPause()
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时调用。

这个方法往往用来提交未保存的改变使之持久化,停止动画和其他消耗CPU的事情等等

不管怎样它应该迅速的执行完毕,因为下一个activity要等到它返回后才会重新使用。

如果activity返回到前面,后面则跟着onResume(),否则它对用户不可见,后面跟着onStop()

yesonResume()或者onStop()
onStop()

Called when the activity is no longer visible to the user. 

This may happen because it is being destroyed, or because another activity (either an existing one or a new one) has been resumed and is covering it.

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


当activity不再对用户可见时调用

它将要被销毁时或者另一个activity重新复用后正在覆盖它时会发生。

如果返回与用户交互,后面跟着onRestart(),否则如果activity正在消失,后面跟着onDestroy()

yesonRestart()或者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


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中任何其他代码。

三个方法标记了“yes”: (onPause(), onStop(), and onDestroy()). 

因为onPause()是三个中的第一个,一旦建立了activity,onPause()是最后一个能保证进程被杀死之前能被调用的函数 - 如果系统必须紧急恢复内存的话,那么onStop()和onDestroy()也许不会被调用。

因此,你应该使用onPause()存储关键的持久性数据(如用户编辑)。

然而,在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 time onResume() is called. 

It will not again be killable until onPause() is again called and returns.

在Killable这列标记“No”的方法从被调用的时刻起保护这activity的进程不被杀死。

因此,一个activity从onPause()返回到onResume()是可以被杀死的。

直到onPause()被调用和返回,他才会再次成为可杀死的。




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也许依然会被杀死 - 但是只会发生在当没有其他依赖极端环境下。

当activity可能会被杀死的更多讨论在“进程和线程”文档中。




Saving activity state

保存activity状态

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.

管理Activity生命周期的介绍简洁的提到当activity处于暂定或者停止状态时,activity的状态被保存着。

这是事实,因为当Activity处于暂停或停止状态时,Activity对象仍然保存在内存中 - 所有它的成员信息和当前状态仍然活着。

因此,任用户在activity内的改变也保存着,所以当activity返回到前台(当它“重新开始”时),那些改变依然在那。



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状态最重要的信息被保存下来。



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 both onCreate() 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 Bundle passed to you is null (which is the case when the activity is created for the first time).

在系统使得activity从脆弱到灭亡之前,调用onSaveInstanceState()

系统传递一个使用例如putString()和putInt()方法的你可以保存状态信的Bundle键值对到这个方法中。

然后,如果系统杀死了你的应用进程并且用户导航回到你的activity中,系统重新建立这个activity并且传递这个Bundle到onCreate()和onRestoreInstanceState()方法中。

使用这两个方法的任意一个,你可以从Bundle中分离出你保存的状态然后恢复activity状态。

如果没有状态信息恢复,那么传递给你的Bundle是null(当你的activity第一次建立的时候就是这种情况)。


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.

两种方式activity带着其完整的状态返回到用户焦点:要么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 calls onSaveInstanceState(), it does so before onStop() and possibly before onPause().

注意:不保证onSaveInstanceState()会在你的activity销毁之前被调用,因为有许多情况是没有必要保存状态的(例如当用户使用back键离开你的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调用允许每一个view提供它自己应该保存的信息的相应的onSaveInstanceState()方法。

几乎每一个在Android framework中的widget都恰当的实现了这个方法,这样任何UI上可见的变化都会自动的保存并且当你的activity重新建立的时候被恢复。

例如,EditText部件保存用户输入的任何文本,CheckBox保存它是否被选中。

唯一要求你完成的工作是为每一个你想保存状态的部件提供一个唯一ID(使用android: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的UI有用的信息,你仍然也许需要覆盖它来保存更多的信息

例如,你也许需要保存成员在activity的生命期间改变的值(与UI中恢复的值相关,但是默认的,成员变量保存的这些UI值没有恢复)


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

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

通过设置android:saveEnabled属性为false或者调用setSaveEnabled()方法,你也可以精确的阻止一个你布局中的view保存它的状态

通常,你不应该使之失效,除非如果你想别具一格的恢复activity的UI状态。

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



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 supercall implementation of onRestoreInstanceState() if you override it, so the default implementation can restore view states.

因为onSaveInstanceState()的默认实现为保存UI状态提供帮助,如果你因要保存额外的状态信息覆盖这个方法,在做任何工作之前,你应该总是调用父类onSaveInstanceState()的实现。

同样的,如果你覆盖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重新建立时,你的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 using onSaveInstanceState() and onRestoreInstanceState() (or onCreate()), as discussed in the previous section.

处理重启最好的方式是使用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

协调activity

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并没有完全的停止是很重要的

启动第二个的进程与停止第一个的进程部分重叠。



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 A启动Acivity B的操作顺序如下:


1.Activity A's onPause() method executes.

A的onPause()方法执行。


2.Activity B's onCreate(), onStart(), and onResume() methods execute in sequence. (Activity B now 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 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 during onStop().

这可预知的生命周期回调顺序运行你管理从一个activity到另一个activity转变的信息。

例如,如果当第一个activity停止时你必须写入数据库,这样接下来的activity就能读取,然后你应该在onPause()期间写入数据库而不是在onStop()期间。



原文地址如下,英文水平实在有限,希望拍砖同时能给予指正。

http://developer.android.com/guide/components/activities.html





转贴请保留以下链接

本人blog地址

http://su1216.iteye.com/

http://blog.csdn.net/su1216/

  相关解决方案