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.
一个Activity
是一个应用组件,它提供了一个屏幕,用户通过此屏幕进行交互操作,并处理一些事情,比如像拔电话,拍照,发邮件,看地图。
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.每个acivity是一个窗口,可以在上面画用户的界面。一般窗口填充整个屏幕,但也可能比屏幕小,并浮于其他窗口上面.
An application usually consists of multiple activities that are loosely bound to each other. 一个应用通常由多个activities组成,它们松散的邦定在一起。
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. 一般,一个应用中指定个activity当作"主"activity,当运行该应用时,它首先呈现给用户
Each activity can then start another activity in order to perform different actions.为了执行不同的activtiy,每个activity可以启动另一个activity.
Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack").
每次一个新的activity开始,选前的activity被停止,但是系统保留这个activity在一个堆中(返回堆)
When a new activity starts, it is pushed onto the back stack and takes user focus. 当一个新的activity开始时,它被压入到返回堆上,并获取用户的焦点
The back stack abides to the basic "last in, first out" queue mechanism, so, when the user is done with the current activity and presses the BACK key, 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
返回堆,遵循“后进,先出”的规则,所以当用处理完当前的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.
当一个activity由于一个新的activity启动而停止时,会通过activity的生命周期回调方法来通知这种状态的改变
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.
一个activity有好几个用于接收的回调方法,这是由于它的改变的状态---是否系统正在创建它,停止它,恢复它,和销毁它---并且每个回调方法提供一个机会,让你根据相应的状态的改变,来做一些特定的工作。
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.
比如,当停止时,你的activity应释放任何的大对象,比如网络或者数据库连接。当一个activity恢复时,你可以重新请求必要的资源并恢复被中断的操作。
These state transitions are all part of the activity lifecycle.这些都是生命周期转换的一部分
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创建一个activity
To create an activity, you must create a subclass of Activity
(or an existing subclass of it).
要创建一个活动,你必须创建一个Activity
子类(或一个已存在的它的子类)
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:
在你的子类中,你需要实现回调方法,当活动转换它的生命周期的各种状态时(比如当活动被创建,停止,恢得或销毁),系统将调用这些回调方法,下面是两个最重要的回调方法:
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.最重要的是,你必须在这里调用setContentView()
方法指定用户界面的布局。
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).
这里常常是你提交那些需要永久保存的改变的地方(因为用户可能会返回来).
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.所有回调方法,在后面的中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.
一个活动的用户界面,是通过view的层级来提供的--从View
类衍生出来的对象.
Each view controls a particular rectangular space within the activity's window and can respond to user interaction.
每个view控制一个方形空间,这里面是一个activity窗口,并能响应用户的交互操作。
For example, a view might be a button that initiates an action when the user touches it.比如,一个view可能是一个按钮,当用户触模它时,触发一个动作。
Android provides a number of ready-made views that you can use to design and organize your layout.
Adnroid提供了大量的准备好的views,你可以用来设计和组织你的布局。
"Widgets" are views that provide a visual (and interactive) elements for the screen, such as a button, text field, checkbox, or just an image.
"Widgets"是一些views,它提供为屏幕提供可视元素,比如一个按钮,文本区,复选框,或只是图片。
"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.
"Layouts"是一些views,它从 ViewGroup
中衍出来,为它的子views提供一个唯一的布局模型,比如线性布局,网格布局,或相对布局。
You can also subclass the View
and ViewGroup
classes (or existing subclasses) to create your own widgets and layouts and apply them to your activity layout.
你可以从View
和ViewGroup
中(或存在的子类)扩展出子类;来创建你自己的widgets和layouts,并应用到你的activity布局中。
The most common way to define a layout using views is with an XML layout file saved in your application resources.
通常是用一个XML布局文件,定义你的视图布局,保存在你的应用资源中。
This way, you can maintain the design of your user interface separately from the source code that defines the activity's behavior.
这样,你能将用户界面的设计与定义activity的行为的代码分开。
You can set the layout as the UI for your activity with setContentView()
, passing the resource ID for the layout. 你可以传一个布局的资源ID,给setContentView()
方法,通过此方法把布局变成你的activity的UI(用户界面)
However, you can also create new View
s in your activity code and build a view hierarchy by inserting new View
s into a ViewGroup
, then use that layout by passing the root ViewGroup
to setContentView()
.
然后,你也可以用activity代码,创建新的视图View
,并且通过将View
插入到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 be accessible to the system. 为了让系统能访问你的activity,你必须在manifest中声明它。
To declare your activity, open your manifest file and add an <activity>
element as a child of the <application>
要声明你的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 the activity, or a theme to style the activity's UI. 在这个元素中,你可以包括一些其他的元素,来定义属性,比如活动的 label,icon,或者activity的UI主题风格.
The android:name
android:name
属性,是唯一必须有的属性—它指定了活动的类名.
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).一旦发布了你的应用,你应不要改变这个名字,因为如果你这样做的话,可能会破坏一些功能。比如像应用的快捷键(读取博客)
See the <activity>
element reference for more information about declaring your activity in the manifest.更多关于在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,当你用SDK工具创建一个新的应用,
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:
将自动为你创建stub activity,包含了一个意图过滤器,它声明了这个activity响应"main"动作,并且应该放在"lanucher"中.
<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. <action>
元素指定了这是应用的主要("main")入点
The <category>
元素指示,这个activity应该列在系统的应用laucher中(运行器)(以允许用户运行这个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.
如果你想让你的应用是独立的(self_contained)并不让其他的应用激活它的活动,那么你不需要任何其也的意图过滤器。
Only one activity should have the "main" action and "launcher" category, as in the previous example. 就如前面的例子,应只有一个活动有"main"动作和"launcher"。
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).你不想让其他应用访问的活动,应该不要有意图过滤器,并且你可以使用显式的意图来声明它(后面将讨论)
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. 对于每个你想要响应的意图类型,你必须包含一个包含了<action>
元素的<intent-filter>
。可选的,一个<category>
元素和/或者<data>
元素
These elements specify the type of intent to which your activity can respond.这些元素指出了你的活动能响应的意图类型。
For more information about how your activities can respond to intents, see the Intents and Intent Filters document.更多关于你的activities能响应的intents,看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. 你可以调用传一个Intent
给startActivity()
方法,启动另一个activity,在Intent
中描述你想要启动的activity.
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). 这个intent,要么描述你想要启动的activity,要么描述你想要执行的动作类型(并且系统为你选一个相应的活动,这个活动可以是其他应用的活动。)
An intent can also carry small amounts of data to be used by the activity that is started.一个意图也可以携带小量的数据,给那个要启动的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
:比如,这里是一个活动怎样启动一个叫做的SignInActivity
活动的例子。
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:
如果有多个活动能处理这个意图,那么用户可以从中选一个。比如,你想允许用户发送一个email消息,你可以创建这样一个间图
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.
这个EXTRA_EMAIL
加入意图的是,要发送到的email地址数组。(recipientArray:即接收邮件的邮件地址数组)
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.
当一个email应用,响应了这个intent,它读取在extra中提供的字串数组,并把它们放到电子邮件表的"to"的域。
In this situation, the email application's activity starts and when the user is done, your activity resumes.
在这种情况下, email应用的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()
).
在那种情况下,调用startActivityForResult()
这个方法启动活动(面不是startActivity()
方法)
To then receive the result from the subsequent activity, implement the onActivityResult()
callback method.
然后,实现onActivityResult()
回调方法为了接收来自后续活动的结果,
When the subsequent activity is done, it returns a result in an Intent
to your onActivityResult()
method.
当后续的活动完成操作,它在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:
比如,也许你想要用户从它们的通信录中,选取一个,以便你的活动可以对其做些处理,下面是你如何创建这样一个意图,并处理返回结果的例子 。
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.
这个例子只是展示了,为了处理一个activity结果,在你的onActivityResult()
方法中应使用的基本逻辑.
The first condition checks whether the request was successful—if it was, then the resultCode
will be RESULT_OK
第一个条件检查请求是否成功——如果是,那么resultCode
将是RESULT_OK
—and whether the request to which this result is responding is known—in this case, the requestCode
matches the second parameter sent with startActivityForResult()
.
并且,检查请求响应的这个结果是否是已知的——在这个例子中,requestCode
匹配第二个参数,它是从startActivityForResult()
发出的
From there, the code handles the activity result by querying the data returned in an Intent
(the data
parameter).
从这里,代码通过查询Intent
中(数据参数)返回的数据,处理活动的返回结果。
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
发生的事情是:一个ContentResolver
执行对内容提供者的查询,这样返回一个Cursor
,它(Cursor
)能使得数据可以被读取,更多详细信息看文档
For more information about using intents, see the Intents and Intent Filters document.更多关于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 separate activity that you previously started by calling finishActivity()
.
调用finish()
方法,你能关闭一个活动,你也可以调用finishActivity()
方法,关闭你先前开启的一个独立的活动
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.
注意:在大多数情况下,你不应显示的用这些方法结束一个活动,像下面部分关于活动的生命周期的讨论 ,Android系统为你管理活动的生命周期,所以不需要自己关闭活动的生命周期,调用这些方法可能对用户体验有不利的影响,并且应该只用于,当你确定不想让用户返回到那个活动的实例时的情况。
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.
一个活动的生命周期直接影响与其关联的其他活动,它的堆和返回堆
An activity can exist in essentially three states:一个活动有三个关键的状态。
Resumed恢复
The activity is in the foreground of the screen and has user focus. (This state is also sometimes referred to as "running".)
活动进入屏幕前台,并捅有用户焦点(这个状态有时候也即是“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.g 一个暂停的活动是完全是有生命的,(这个对象仍驻留在内存中,它维持着所有的状态和内存信息,并关联到窗口管理器)但在内存相当有限的情况可以杀掉。
Stopped停止状态
The activity is completely obscured by another activity (the activity is now in the "background").这个activity完全被另一个activity所湮没(这个activity现在是在"后台")
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.
如果一个活动暂停或者停时了,系统通过要求它完成(调用finish()
方法),或简单的杀掉它的进程,来把它从内存中移除。
When the activity is opened again (after being finished or killed), it must be created all over.当再次打开时(在结束或杀掉后),它必须全部重新创建
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:下面这个骨架活动包括了每个生命周期的基本方法
onCreate
onStart()
onResume()
onPause()
onStop()
onDestroy()
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:
总之,这些方法定义的活动整个生命周期,通过实现这些方法,你能监视活动生命周期的三个嵌套循环。
- The entire lifetime of an activity happens between the call to
onCreate()
and the call toonDestroy()
. - 活动的完整的生命时间发生在调用
onCreate(),
onDestroy()
两个函数之间. - Your activity should perform setup of "global" state (such as defining layout) in
onCreate()
, and release all remaining resources inonDestroy()
. - 你的活动应在
onCreate()
这个方法中执行设置全局状态(比如定义布局),并在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()
方法创建一个线程,并且在onDestroy()
这个方法停止它 - The visible lifetime of an activity happens between the call to
onStart()
and the call toonStop()
. - 一个活的可见的生命时间,发生在调用
onStart()
和调用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. - 比如,当一个新的活动开启,
onStop()
方法被调用,这个活动将不再可见 - 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
inonStart()
to monitor changes that impact your UI, and unregister it inonStop()
when the user can no longer see what you are displaying. - 比如,你可以在
onStart()
中注册一个BroadcastReceiver
,来监视影响你的UI的改变,当用户不再需要看你的显示时在onStop()
中注销它。 - The system might call
onStart()
andonStop()
multiple times during the entire lifetime of the activity, as the activity alternates between being visible and hidden to the user. - 当活动交替着对用户显示或隐藏时,系统可能在活动的整个生命时间之间,多次调用
onStart()
和onStop()
这两个方法。 - The foreground lifetime of an activity happens between the call to
onResume()
and the call toonPause()
. - 活动的前台生命时间,发生在调用
onResume()
和调onPause()
方法之间 - During this time, the activity is in front of all other activities on screen and has user input focus.
- 在这段时间内,这个activity在屏幕上的所有其他活动上,并且捅有用户输入焦点
- 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. - 比如,当设备进入睡眠或当一个对话框出现了,
onPause()
被调用 - 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.
- 因为这个状态经常转换,所以在这两个方法中的代码应该是轻量级的,以避免因为转换慢而导致用户需要等待。
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.
图1说明了活动在状态之间发生转换时的循环和路径,矩形表示回调方法,当活动在状态之间转换时,你可以实现它执行一些操作
Figure 1. The activity lifecycle.活动的生命周期
The same lifecycle callback methods are listed in table 1, 表格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.它详细的描述了每个回调方法,及它在每个活动的生命周期内的定位,包括在回调方法调后完成后,系统是否能杀掉它。
Table 1. A summary of the activity lifecycle's callback methods.活动生命周期回调方法的总结
Method | Description | Killable after? | Next |
| 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 当活动第一次被创建时调用,在这里你应处理所有的静态设置——创建视图,邦定数据到列表,等等,这个方法被传入一个Bundle对象,它包含了活动之前的状态,是否状态被捕获(看后面的Saving Activity State)总是跟着 | No |
|
| Called after the activity has been stopped, just prior to it being started again. Always followed by 当活动停止后调用,只是优先于再次启动之前,总是跟着 | No |
|
| Called just before the activity becomes visible to the user. Followed by 当活动变成对用户可见之前调用,如果活动来自前景跟随着 | No |
or
|
| 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 只是在活动开始与用户交互之前调用,在这时,活动处理活动堆的顶部,用户输入给它。总是跟着 | No |
|
| 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 当系统将要恢复其他的活动时调用,这个方法主要是用于提交没有保存的永久数据的改变,入停止动画和其他可能消CPU的东西,等等。它应快速处理要做事情,因为下一个活动直到它返回后才能恢复。如果活动从后台到前台跟随着 | Yes |
or
|
| 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 当活动对用户不再可见时调用,当发生这处调用时,可能活动正在被销毁,或者另一个活动(一个存在的或一个新的)被恢复,并正在复盖它。如果活动即将与用户交互跟 | Yes |
or
|
| 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 在活动被销毁之前,这是活动将要接收到的最后一个调用。它被调用可能是由于活动正在完成,或者由于系统要保留空间,正在临时性的销毁它。你可以用 | 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.
标有"Killable after?"的列,指示在这些方法调用返回后,系统是否能杀掉捅用该activity的进程,而不执行活动代码的其他行。
Three methods are marked "yes": (onPause()
, onStop()
, and onDestroy()
). 三个方法被标记了"yes": (onPause()
, onStop()
, and onDestroy()
).
Because onPause()
is the first of the three, once the activity is created,由于onPause()
方法是三个中的第一个( 难以理解这句话的要表达什么),一旦活动被创建
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,
在进程被kill前,onPause()
方法是最后个保证会被调用的方法---如果系统在紧急情况下必须回收内存时
then onStop()
and onDestroy()
might not be called. 然后是onStop()
和onDestroy()
方法可能不会被调用到
Therefore, you should use onPause()
to write crucial persistent data (such as user edits) to storage.因此,你应该用onPause()方法
去把一些关键数据写到存储器中
However, you should be selective about what information must be retained during onPause()
, 但是,在onPause()
方法中,你应该选择性保存那些必须要记住的的信息
because any blocking procedures in this method block the transition to the next activity and slow the user experience.
因为这个方法中的任何的阻塞过程,阻止转换到下一个活动,并因此降低了用户的体验
Methods that are marked "No" in the Killable column protect the process hosting the activity from being killed from the moment they are called.
在Killable 列,标记为”No”的方法,从它们被调用的那一刻开始,保护持有将被杀活动的进程,
Thus, an activity is killable from the time onPause()
returns to the time onResume()
is called.
因此,一个活动在onPause()
方法那一刻,到返回onResume()
方法被调用那一刻之间,是可以被杀掉的.
It will not again be killable until onPause()
is again called and returns. 直到onPause()
方法再次被调用和返回之前,它将不能再次被杀掉
Note: An activity that's not technically "killable" by this definition in table 1 在表1中定义的,一个活动不是技术上的”可以杀掉(killable)”,
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
在Processes and Threading
Saving activity state保存活动状态
The introduction to Managing the Activity Lifecycle
Managing the Activity Lifecycle介绍中,简单的提及了,当一个活动被暂停或停止时,活动的状态仍驻留.
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.
这是真的,因为当Activity
对象被暂停或停止时,它仍驻留在内存---所有它的成员和当前状态信息仍是活的(alive).
Thus, any changes the user made within the activity are retained in memory, 因此,用户对活动的任何改变被驻留在内存中.
so that when the activity returns to the foreground (when it "resumes"), those changes are still there.所以当该活动返回到前台(当它被恢复”resume”)时,这些改变仍在那儿。
Figure 2. The two ways in which an activity returns to user focus with its state intact: either the activity is stopped, then resumed and the activity state remains intact (left), or the activity is destroyed,then recreated and the activity must restore the previous activity state (right)图中有两种方法,一个活动带着它原有的状态返回到用户焦点。要么活动被停止,然后恢复,该活动的状态恢复原样(左图),或者活动被销毁,然后重新创建,并且该活动必须重新恢复先前的活动状态.
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.
但,当系统为了回收内存,而销毁了一个活动,这个Activity
对象被销毁了,所以系统不能简单的恢复它原有的状态。
Instead, the system must recreate the Activity
object if the user navigates back to it. 而是,如果用户导航返回它时,系统必须重新创建Activity
对象.
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 and then restore it when the the system recreates the activity.
你可以通过实现一个附加的方法,它能允许你保存你活动的状态信息,然后当系统重创建活动时并且能恢复活动的状态,以确保你的活动的重要信息被保存了.
The callback method in which you can save information about the current state of your activity is onSaveInstanceState()
.
有一个你能在那里,保存你的活动当前状态的方法是onSaveInstanceState()
.方法.
The system calls this method before making the activity vulnerable to being destroyed and passes it a Bundle
object.
系统在使得某活动变得容易被销毁之前,调用这个方法,并传一个Bundle
对象给它.
The Bundle
is where you can store state information about the activity as name-value pairs, using methods such as putString()
.
你可以在Bundle
那儿,把你的活动的相关信息当成一个名字值对(name-value pairs)保存起来,通过使用类似于putString()
的方法
Then, if the system kills your activity's process and the user navigates back to your activity, the system passes the Bundle
to onCreate()
so you can restore the activity state you saved during onSaveInstanceState()
.
然后,如果系统杀掉了你的活动的进程,并且用户导航返回到你的活动时,系传一个Bundle
给onCreate()
方法,以便你能重新恢,你在onSaveInstanceState()
中保存的活动的状态.
If there is no state information to restore, then the Bundle
passed to onCreate()
is null.如果没有状态信息要恢得,那么传给onCreate()
方法的Bundle
是null值
Note: There's no guarantee that onSaveInstanceState()
will be called before your activity is destroyed,
注意,不能保证在你的活动被销毁前,onSaveInstanceState()
方法将被调用
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 key, because the user is explicitly closing the activity).
当用户使用返回键离开你的活动时,因为用户明显要关掉你的活动
If the method is called, it is always called before onStop()
and possibly before onPause()
.
如果这个方法被调用,它将经常在调用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()
.
然后,即使你没有做任保事,或没有实现onSaveInstanceState()
方法,一些活动的状态将被类的onSaveInstanceState()
方法的默认实现恢复
Specifically, the default implementation calls onSaveInstanceState()
for every View
in the layout, which allows each view to provide information about itself that should be saved. 特别是,默认实现为每一个布局中的View
调用onSaveInstanceState()
方法,这样允许每个view提供关于它自己需要保存的信息
Almost every widget in the Android framework implements this method as appropriate, 几乎Android框架的每个widget,都相应的实现了这个方法.
such that any visible changes to the UI are automatically saved and restored when your activity is recreated.
比如当你的活动被重创建时,对UI任何可见的改变将自动保存和恢复
For example, the EditText
widget saves any text entered by the user and the CheckBox
widget saves whether it's checked or not.
比如,EditText
widget保存了你输入的任何文本,并CheckBox
widget保存了是否它被复选。
The only work required by you is to provide a unique ID (with the android:id
你必须要做的唯一工作是,为每一个你想保存它的状态的widget提供一个唯一的ID(使用android:id
这个属性).
If a widget does not have an ID, then it cannot save its state.如个widget没有ID,那么它的状态将不能被保存
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.你也可以显式的阻止你的布局保存它的状态,通过设置android:saveEnabled
属性为”false”,或调用方法设置它为”false”.Usually, you should not disable this, but you might if you want to restore the state of the activity UI differently。通常,你不应禁止这个功能,但如果你想恢复UI的不同状态,你可以这么做.
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.虽然onSaveInstanceState()
方法的默认实现保存了,你的活动的UI的有用的信息,你仍可能需要复写它,保存另外的信息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).比如,你可能需要保存在活动生命周期改变的成员值,(这些值,可能是与恢得UI相关的值,但一般情况下,成员保存的这些UI值不需要恢复)Because the default implementation of onSaveInstanceState()
helps save the state of the UI, 因为,onSaveInstanceState()
方法的默认实现帮助保存了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.如果你要复写这个方法,来保存另外的状态信息,你应该总在,做任何其他事情之前调用超类的onSaveInstanceState()
方法.
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)—注意:因为onSaveInstanceState()
方法不能保证被调用,所以你应仅仅用它记录活动的暂时的状态(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.你不应用它存储持久数据,而是,当用户离开活动时,你应用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 orientation.当屏幕方向发生改变时,系统为了应用对新的屏幕方向可选取的资源,它将销毁并重新创建该活动。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.就这一理由,就足以说明,当活动被重新创建时,你的活动能完全恢复它的状态非常重要,因为在使用应用时,用户常常转动屏幕。
Handling configuration changes处理配置的变化
Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language).一些设备的配在运行时可能会改变,(比如屏幕方向,键盘功能,和语言)When such a change occurs, Android restarts the running Activity (onDestroy()
is called, followed immediately by onCreate()
).当这些改变发生时,Android重新启动运行中的Activity(在onDestroy()
方法调用后,立即紧跟着调用onCreate()
方法).The restart behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources that you've provided.重启行为,通过自动装载你提供的应用的可选资源,帮助你的应用适应新的配置If you design your activity to properly handle this event, it will be more resilient to unexpected events in the activity lifecycle.如果你设置你的活动去相应的处理这些事件,在活动的生命周期中,将会有更多的意料不到的事件会反弹。
The best way to handle a configuration change, such as a change in the screen orientation, is to simply preserve the state of your application using onSaveInstanceState()
and onRestoreInstanceState()
(or onCreate()
), as discussed in the previous section.处理这种配置改变(比如屏幕方法改变)的最好方法,就是像前面章节讨论的,使用onSaveInstanceState()
方法和onRestoreInstanceState()
方法(或onCreate()
方法)简单的预保留你的应用的状态.
For a detailed discussion about configuration changes that happen at runtime and how you should handle them, read 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.更进一步来说,开启第二个活动的过程和停止第一个活动的过程是重叠的.
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: 生命周期的回调方法的顺序是很好确定的,特别是在同一个进程中,一个活动开启另一个活动时.这里是当活动A启动活动B 时操作的顺序.
- Activity A's
onPause()
method executes. 活动A的方法执行 - Activity B's
onCreate()
,onStart()
, andonResume()
methods execute in sequence. (Activity B now has user focus.) - 活动B的
onCreate()
,onStart()
, 和onResume()
方法按顺执行(这时活动B捅有用户焦点) - 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()
.比如,如果当第一个活动加停止时,你必须写入到数据库,以备后面的活动读取它,那么你应在onPause()
方法写入到数据库,而不是在onStop()
.方法中.