标签:
Creating an Activity 创建一个Activity
Implementing a user interface 实现用户界面
Declaring the activity in the manifest 在清单文件中声明Activity
Starting an Activity 启动一个Activivty
Starting an activity for a result 启动一个Activity得到结果
Shutting Down an Activity 关闭Activity
Managing the Activity Lifecycle 管理Activity的生命周期
Implementing the lifecycle callbacks 实现生命周期的回调
Saving activity state 保存activity的状态
Handling configuration changes 处理配置的修改
Coordinating activities Activity之间的协作
Activity
Tasks and Back Stack
An Activity
is an application component that provides a screen with which users can interact in order to do something,
such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface. The window typically fills the screen, but may be smaller than the screen and float on top of other windows.
Activity是一个应用程序组件,它提供了为做一些事情与用户交互的屏幕,如拨打电话,拍照,发送电子邮件,或查看地图。每个Activity都被给予了一个窗口绘制它的用户界面。通常窗口填充屏幕,但是总是小于屏幕,浮动在其他窗口上。
An application usually consists of multiple activities that are loosely bound to each other. Typically, one activity in an application is specified as the "main" activity, which is presented to the user when launching the application for the first time. Each activity can then start another activity in order to perform different actions. Each time a new activity starts, the previous acti看vnmvity is stopped, but the system preserves the activity in a stack (the "back stack"). When a new activity starts, it is pushed onto the back stack and takes user focus. The back stack abides to the basic "last in, first out" stack mechanism, so, when the user is done with the current activity and presses theBack button, it is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is discussed more in theTasks and Back Stack document.)
一个应用程序通常由松散绑定的多个Activity组成。通常,一个应用程序中的Activity被指定为“主”Activity,这是在第一次启动应用程序的时候提供给用户。每个Activity都可以启动另一个Activity以执行不同的动作。每一次新的Activity开始,以前的Activity停止,系统把Activity保存在堆栈中 (“回栈”)。当一个新的活动开始,它被推到返回堆栈中和失去用户焦点。回堆栈遵守基本的“后进,先出堆栈机制,因此,当用户完成当前Activity并按下返回按钮,则弹出堆栈(和破坏)和恢复前一个活动。(后退堆栈进行了更多的任务和后退堆栈文档。)
When an activity is stopped because a new activity starts, it is notified of this change in state through the activity‘s lifecycle callback methods. There are several callback methods that an activity might receive, due to a change in its state—whether the system is creating it, stopping it, resuming it, or destroying it—and each callback provides you the opportunity to perform specific work that‘s appropriate to that state change. For instance, when stopped, your activity should release any large objects, such as network or database connections. When the activity resumes, you can reacquire the necessary resources and resume actions that were interrupted. These state transitions are all part of the activity lifecycle.
当一个Activity停止,由于一个新的Activity开始的时候,它是通过活动的生命周期回调方法,通知这种状态的改变。一个Activity可以接收有几个回调方法,系统根据其状态的变化判断是否创建它,阻止它,恢复它,或摧毁它.每一次回调提供您机会完成特定的工作以适应状态的改变。例如,当停止,你的活动应该释放大型对象,如网络或数据库连接。当活动恢复,你可以重新获得必要的资源和恢复被中断的动作。这些状态转换是Activity的所有的生命周期。
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状态间的转换。
To create an activity, you must create a subclass of Activity
(or an existing subclass of it). In your subclass,
you need to implement callback methods that the system calls when the activity transitions between various states of its lifecycle, such as when the activity is being created, stopped, resumed, or destroyed. The two most important callback methods are:
创建一个Activity,你必须创建一个Activity的子类(或现有的子类)。子类中,当其生命周期的不同状态之间的转换Activity的时候,你需要实现系统调用的回调方法。例如创建Activity时,停止,恢复或销毁。最重要的两个回调方法:
onCreate()
You must implement this method. The system calls this when creating your activity. Within your implementation, you should initialize the essential components of your activity. Most importantly,
this is where you must call setContentView()
to define the layout for the activity‘s user interface.
您必须实现这个方法。当创建Activity的时候系统调用这个方法。在你实现中,你应该初始化Activity的基本要素。最重要的是,你必须调用setContentView()来定义Activity的用户界面的布局。
onPause()
The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).
系统调用此方法作为第一个迹象表明用户离开你Activity(尽管它并不总是意味着Activity销毁了)。这通常是你应该提交的任何更改,应保存在当前用户会话(因为用户可能不回来)。
There are several other lifecycle callback methods that you should use in order to provide a fluid user experience between activities and handle unexpected interuptions that cause your activity to be stopped and even destroyed. All of the lifecycle callback methods are discussed later, in the section about Managing the Activity Lifecycle.
还有其他几个生命周期回调方法,您应该使用Activity之间为了提供流畅的用户体验和处理意外中导致你的Activity停止,甚至毁灭。稍后将讨论所有的生命周期回调方法,在下一节关于管理Activity生命周期。
The user interface for an activity is provided by a hierarchy of views—objects derived from the View
class. Each
view controls a particular rectangular space within the activity‘s window and can respond to user interaction. For example, a view might be a button that initiates an action when the user touches it.
一个Activity的用户界面是由视图-对象衍生的视图类的层次结构。每个视图控制特定的矩形空间内Activity的窗口,可以响应用户交互。例如,一个视图可能是一个按钮,当用户触摸它启动一个动作。
Android provides a number of ready-made views that you can use to design and organize your layout. "Widgets" are views that provide a visual (and interactive) elements for the screen, such as a button, text field, checkbox, or just an image. "Layouts" are views
derived from ViewGroup
that provide a unique layout model for its child views, such as a linear layout, a grid
layout, or relative layout. You can also subclass the View
and ViewGroup
classes
(or existing subclasses) to create your own widgets and layouts and apply them to your activity layout.
Android提供了许多现成的视图,您可以使用它们来设计和组织你的布局。“窗口小部件”视图,提供一个屏幕视觉和互动元素,比如一个按钮,文本字段、复选框,或只是一个形象。“布局”视图来自ViewGroup提供一个独特的子视图的布局模型,如线性布局,网格布局,或相对布局。您还可以使用子类视图和ViewGroup类(或现有的子类)来创建自己的小部件和布局,将它们应用到Activity。
The most common way to define a layout using views is with an XML layout file saved in your application resources. This way, you can maintain the design of your user interface separately from the source code that defines the activity‘s behavior. You can set
the layout as the UI for your activity with setContentView()
, passing the resource ID for the layout. However,
you can also create new 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
tosetContentView()
.
定义一个布局的一般方式是使用保存在应用资源中的xml文件。使用这种方式,你可以保持用户界面的设计和activity动作的源码分开。你可以使用setContentView(),通过布局的资源ID,设置activity的布局。你也可以在activity中创建一个视图类,通过在视图组中插入新视图来实现,来构建一个视图树。根视图组通过setContentView()设置。
For information about creating a user interface, see the User Interface documentation.
创建用户界面的更多信息,看下用户界面的文档。
You must declare your activity in the manifest file in order for it to be accessible to the system. To declare your activity, open your manifest file and add an <activity>
element
as a child of the <application>
element. For example:
你必须在清单文件中声明Activity,以便它可以访问系统。打开你的清单文件,声明你的activity,在 <application>元素中添加一个<activity>的子元素。例如:
<manifest ... > <application ... > <activityandroid:name=".ExampleActivity"/> ... </application ... > ...</manifest>
There are several other attributes that you can include in this element, to define properties such as the label for the activity, an icon for the activity, or a theme to style the activity‘s UI. The android:name
attribute
is the only required attribute—it specifies the class name of the activity. Once you publish your application, you should not change this name, because if you do, you might break some functionality, such as application shortcuts (read the blog post, Things
That Cannot Change).
还有其他几种属性,您可以包括在这个元素中,为activity定义属性标签,活动的图标,或一个主题风格的UI。android: name是唯一指定的类名。一旦发布您的应用程序,您不应该改变这个名字,因为如果你这样做,你可能会打破一些功能,如应用程序快捷键(阅读博客,不能改变的事情)。
See the <activity>
element reference for more information about declaring your activity in the manifest.
在清单文件中声明activity更多信息,你可以查看应用清单的<activity>元素相关。
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>元素还可以指定各种意图filters-using < intent-filter >元素,来声明其他应用程序组件如何激活它。
When you create a new application using the Android SDK tools, the stub activity that‘s created for you automatically includes an intent filter that declares the activity responds to the "main" action and should be placed in the "launcher" category. The intent filter looks like this:
当你使用Android SDK工具创建一个新的应用程序,自动为你创建一个Activity,包括一个意图过滤器,声明Activity响应的“主要”行动和类别。意图过滤器如下所示:
<activityandroid:name=".ExampleActivity"android:icon="@drawable/app_icon"> <intent-filter> <actionandroid:name="android.intent.action.MAIN"/> <categoryandroid:name="android.intent.category.LAUNCHER"/> </intent-filter></activity>
The <action>
element specifies that this is the "main" entry point to the application. The <category>
element
specifies that this activity should be listed in the system‘s application launcher (to allow users to launch this activity).
If you intend for your application to be self-contained and not allow other applications to activate its activities, then you don‘t need any other intent filters. Only one activity should have the "main" action and "launcher" category, as in the previous example. Activities that you don‘t want to make available to other applications should have no intent filters and you can start them yourself using explicit intents (as discussed in the following section).
如果你想让你的应用程序是独立的,不允许其他应用程序来激活它的Activity,那么你不需要任何其他意图过滤器。只有一个Activty应该有动作和分类。如前面的例子。如果你不想让Acitivity响应其他应用程序,你可以启动他们,你可以自己使用显式意图(在下一节中讨论)。
However, if you want your activity to respond to implicit intents that are delivered from other applications (and your own), then you must define additional intent filters for your activity. For each type of intent to which you want to respond, you must include
an <intent-filter>
that includes an <action>
element
and, optionally, a<category>
element and/or a <data>
element.
These elements specify the type of intent to which your activity can respond.
然而,如果你希望你的Activity来应对隐含的意图,与其他应用程序区分开,那么你必须定义额外的意图过滤器为您的activity。为你想回应每种类型的意图,您必须包含一个< intent-filter >,包含一个<action>元素,<category>元素或一个<data>元素。这些元素指定类型的activity可以回应你的意图。
For more information about how your activities can respond to intents, see the Intents and Intent Filters document.
activity响应意图的更多信息,你可以查看 Intents and Intent Filters 文档
You can start another activity by calling startActivity()
, passing it an Intent
that
describes the activity you want to start. The intent specifies either the exact activity you want to start or describes the type of action you want to perform (and the system selects the appropriate activity for you, which can even be from a different application).
An intent can also carry small amounts of data to be used by the activity that is started.
你可以通过调用startactivity()启动另一个acitity,它传递一个意图,描述你想启动的activity。目的指定确切的activity你想开始或描述你想执行的操作类型(系统会选择合适的Activity给你,它甚至可以在不同的应用中)。一个意图也可以包含少量的数据在被启动的Activity中使用的。
When working within your own application, you‘ll often need to simply launch a known activity. You can do so by creating an intent that explicitly defines the activity you want to start, using the class name. For example, here‘s how one activity starts another
activity named SignInActivity
:
当你自己的应用程序在运行时,你需要经常地推出一个已知的activity。你可以通过创建一个意图,明确定义了你想启动的activity,使用类名称。例如,这里有一个activity启动另一个Activity:
Intent intent =newIntent(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:
然而,你的应用程序可能还需要执行一些动作,如发送电子邮件,文本消息,或状态更新,使用来自你的activity的数据。在这种情况下,你的应用程序可能没有执行该动作的activity,所以你可以利用设备上的其它应用程序提供的activity,它能为你执行动作。意图的真正价值是你可以创建一个意图,描述你想执行的动作,系统从另一个应用程序启动适当的activity。如果有多个可以处理意图的Activity,然后用户可以选择使用一个。例如,如果你想让用户发送电子邮件,您可以创建以下目的:
Intent intent =new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, recipientArray); startActivity(intent);
The EXTRA_EMAIL
extra added to the intent is a string array of email addresses to which the email should be sent.
When an email application responds to this intent, it reads the string array provided in the extra and places them in the "to" field of the email composition form. In this situation, the email application‘s activity starts and when the user is done, your activity
resumes.
该 EXTRA_EMAIL 额外添加到意图是一个字符串数组的邮件地址,发送电子邮件。当一个电子邮件应用程序响应这个意图,它读取额外提供的字符串数组,并将它们放在电子邮件表字段。在这种情况下,电子邮件应用程序的activity开始,当用户完成,你的活动恢复。
Sometimes, you might want to receive a result from the activity that you start. In that case, start the activity by calling startActivityForResult()
(instead
of startActivity()
). To then receive the result from the subsequent activity, implement the onActivityResult()
callback
method. When the subsequent activity is done, it returns a result in an Intent
to your onActivityResult()
method.
有时,你可能想从你开始activity得到的结果。在这种情况下,通过调用startactivityForResult()启动Acitivity(而不是startactivity())。然后接收来自后续Activity的结果,实现onActivityResult()回调方法。当随后Activity完成,它返回在意向你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:
例如,你可能想让用户选择一个联系人,那么你的Activity可以通过在联系人中得到的信息做某事。这里是你如何创造这样的意图和处理结果:
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(), newString[]{Contacts.DISPLAY_NAME},null,null,null); if(cursor.moveToFirst()){// True if the cursor is not empty int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME); String name = cursor.getString(columnIndex); // Do something with the selected contact‘s name... } }}
This example shows the basic logic you should use in your onActivityResult()
method in order to handle an activity
result. The first condition checks whether the request was successful—if it was, then the resultCode
will be 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()
. From there, the code handles the activity result by querying the
data returned in an Intent
(the data
parameter).
这个例子表明,你应该用你的onActivityResult()方法以处理Acitivity的结果的基本逻辑。第一个条件检查请求是否成功,如果是,那么ResultCode是 RESULT_OK,并且
是否请求的响应结果是已知在这种情况下,requestCode匹配发送startActivityForResult()第二个参数。从那里,代码处理Activity的结果通过查询数据的意图返回(数据参数)。
What happens is, a ContentResolver
performs a query against a content provider, which returns a Cursor
that
allows the queried data to be read. For more information, see the Content Providers document.
所发生的是,一个ContentResolver执行对内容提供商的查询,并返回一个指针,允许读取被查询的数据。有关更多信息,请参见内容提供者文档。
For more information about using intents, see the Intents and Intent Filters document.
关于使用意图的更多信息,请参见意图和意图过滤器文件。
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()
.
你可以关闭一个activity,通过调用它的finish()方法。你也可以关闭一个单独的activity,在以前通过调用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.
注意:在大多数情况下,你不应该明确使用这些方法关闭Activity。在下一节讨论关于活动的生命周期,Android系统为你管理一个activity的生命,所以你不需要关闭自己的Activity。调用这些方法可能产生不利影响的预期的用户体验,应该只用于当你绝对不希望用户返回到该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,其任务和后退堆栈。
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".)
acitivity是在屏幕的前台和拥有用户焦点。
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的顶部可见或部分透明或没有覆盖整个屏幕。这个暂停的activit依然存活(Activity对象保留在内存中,它保持所有状态和成员信息,并保持附着到窗口管理器),但在极低的内存的情况下,可以被系统杀死。
Stopped
The activity is completely obscured by another activity (the activity is now in the "background"). A stopped activity is also still alive (the Activity
object
is retained in memory, it maintains all state and member information, but is not attached to the window manager). However, it is no longer visible to the user and it can be killed by the system when memory is needed
elsewhere.
activity是由另一个activity完全遮蔽(activity现在在“背景”)。停止activity也仍然活着(activity对象保留在内存中,它保持所有状态和成员信息,但没有连接到窗口管理器)。然而,它是用户不可见的,在其它地方需要内存时它可以被系统杀死。
If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling itsfinish()
method),
or simply killing its process. When the activity is opened again (after being finished or killed), it must be created all over.
如果activity被暂停或停止时,系统能够将它从内存中关闭掉(调用它的finish()法),或简单地杀死它的进程。当activity再次被打开(完成的或杀死之后),它必须所有的重新建立。
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过渡到了上述不同的状态,它是通过调用不同的回调方法。所有的回调方法你可以重载做适当的工作。下面包括每个基本周期的方法:
publicclassExampleActivityextendsActivity{ @Override publicvoidonCreate
(Bundle savedInstanceState){ super.onCreate(savedInstanceState); // The activity is being created. } @Override protectedvoidonStart()
{ super.onStart(); // The activity is about to become visible. } @Override protectedvoidonResume()
{ super.onResume(); // The activity has become visible (it is now "resumed"). } @Override protectedvoidonPause()
{ super.onPause(); // Another activity is taking focus (this activity is about to be "paused"). } @Override protectedvoidonStop()
{ super.onStop(); // The activity is no longer visible (it is now "stopped") } @Override protectedvoidonDestroy()
{ super.onDestroy(); // The activity is about to be destroyed. }}
Note: Your implementation of these lifecycle methods must always call the superclass implementation before doing any work, as shown in the examples above.
注意:你的这些生命周期方法的实现之前,做任何工作必须调用基类的实现,如上面的示例所示。
Taken together, these methods define the entire lifecycle of an activity. By implementing these methods, you can monitor three nested loops in the activity lifecycle:
综合起来,这些方法定义一个activity的整个生命周期。通过实施这些方法,你可以监视activity周期的三个嵌套循环:
The entire lifetime of an activity happens between the call to onCreate()
and
the call to onDestroy()
. Your activity should perform setup of "global" state (such as defining layout) in onCreate()
,
and release all remaining resources in onDestroy()
. For example, if your activity has a thread running in the
background to download data from the network, it might create that thread in onCreate()
and then stop the thread
inonDestroy()
.
一个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并与它进行交互。例如,当一个新的活动调用onstop(),它是一个不可见的。这两个方法之间,你可以保持activity需要显示给用户的资源。例如,您可以注册一个BroadcastReceiver的 onstart()监视影响你的用户界面的变化,当用户无法看到你的显示的时候,你可以在在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.
图1显示了这些圆形代表activity的状态之间转换的路径。矩形代表你可以实现不同状态转换时,回调方法的执行顺序。
Figure 1. The activity lifecycle.
The same lifecycle callback methods are listed in table 1, which describes each of the callback methods in more detail and locates each one within the activity‘s overall lifecycle, including whether the system can kill the activity after the callback method completes.
相同的生命周期回调方法表1中列出,详细描述每一个回调方法和定位中的每一个活动的整体生命周期,包括系统是否可以杀死活动完成后的回调方法。
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 当activity首次创建。这里你应该处理静态设置。比如创建视图,将数据绑定到列表等。如果状态可以被捕获,这种方法是通过Bundle可以得到activity的先前状态。(见Activity保存状态)。总是跟着onstart()。 |
No |
onStart() |
||
|
|
Called after the activity has been stopped, just prior to it being started again.
Always followed by
|
No |
onStart() |
|
|
Called just before the activity becomes visible to the user.
Followed by 就在activity变得可见的时候调用。如果之后前台可见,调用onResume。如果不可见调用onStop()。
|
No |
onResume() or onStop() |
||
|
|
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 在activity将要与用户的交互的时候调用。此时activity是在activity堆栈的顶部,而且正在得到用户的输入。总是跟着onPause()。
|
No |
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 当系统开始恢复另一个activity。这种方法通常用于提交未保存的更改的持久化数据,停止动画和可能消耗CPU的其他动作等。它应该非常快,因为只有它返回,其他的activity才能恢复。另外的activtiy返回到前台,将调用onResume,否则讲调用onStop()。 |
Yes |
onResume() or 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 当activity不再可见。这可能是因为它被破坏,或者因为另一个activity(无论是现有的或新的)已经恢复并覆盖。若activity与用户交互调用onRestart(),如果activity销毁通过调用onDestroy()。 |
Yes |
onRestart() or 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 onDestroy() 销毁actvity之前调用。activity最后能接收到的调用方法。可能是activity已经完成(有人调用finish()),或者因为系统暂时破坏该activity实例的节省空间。你能区分这两种情况的isfinishing()方法。. |
Yes | nothing |
The column labeled "Killable after?" indicates whether or not the system can kill the process hosting the activity at any time after the method returns, without executing another line of the activity‘s code. Three
methods are marked "yes": (onPause()
, onStop()
,
and onDestroy()
). Because onPause()
is
the first of the three, once the activity is created, onPause()
is the last method that‘s guaranteed to be called
before the process can be killed—if the system must recover memory in an emergency, then onStop()
and onDestroy()
might
not be called. Therefore, you should use onPause()
to write crucial persistent data (such as user edits) to storage.
However, you should be selective about what information must be retained during onPause()
, because any blocking
procedures in this method block the transition to the next activity and slow the user experience.
列标记为“之后被杀死“显示系统是否在主activity方法返回后可以主进程随时杀死,不会执行activity的其他代码。三种方法被标记为“是”:(onPause(),onStop(),和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 timeonResume()
is called. It will not again be killable until onPause()
is
again called and returns.
方法标记Killable列保护过程中的“不”的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可能会杀死.更多的讨论进程和线程文档。
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是否能恢复到原来的状态。在这种情况下,你可以确保关于活动状态的重要信息是通过执行一个附加的方法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()
andonRestoreInstanceState()
.
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()保存数据
。该系统通过传递一个Bundle,你能通过键值对的方式保存activity信息使用方法,如putstring()和putint()。然后,如果系统杀死你的应用程序,当你返回到你的activity的时候,系统会重新创建activity,通过对onCreate()和onRestoreinstancestate()提取你保存的状态和恢复活动状态。如果没有状态信息恢复,Bundle为空(这种情况时,活动是在第一次创建)。
Figure 2. The two ways in which an activity returns to user focus with its state intact: either the activity is destroyed, then recreated and the activity must restore the previously saved state, or the activity is stopped, then resumed and the activity state remains intact.
这两种方法让activity返回用户焦点:要么销毁activity,然后创建activity,必须恢复以前保存的状态,或者停止活动,然后恢复activity状态保持不变。
Note: There‘s no guarantee that onSaveInstanceState()
will be called
before your activity is destroyed, because there are cases in which it won‘t be necessary to save the state (such as when the user leaves your activity using the Back button, because the user is explicitly closing
the activity). If the system callsonSaveInstanceState()
, it does so before onStop()
and
possibly before onPause()
.
在activtity被销毁之前,actvity不能保证onSaveInstanceState()调用。因为在这种情况下,它不会是必要的保存状态(例如,当用户离开你的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()实现恢复。具体来说,默认实现调用布局中的每个视图对应的onSaveInstanceState()方法,允许每个视图提供关于自身的信息应保存。在Android框架几乎每一个部件实现这个适当的方法,使得对用户界面的任何可见的变化进行自动保存和恢复你的activity被重新创建。例如,EditText小部件保存任何文本由用户和复选框控件保存它是否被选择。你唯一需要的工作是提供一个独特的ID(与Android:id属性)为每个控件你想保存其状态。如果插件没有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 thesetSaveEnabled()
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,或调用setSaveEnable()。一般情况下,你不该禁用它。但你想使你的activity在恢复状态时,有不同的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. 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).
尽管默认的保存activity界面的有用信息的onSaveInstanceState(),你仍然可能需要重写它。例如,您可能需要在恢复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 superclass implementation of onRestoreInstanceState()
if you
override it, so the default implementation can restore view states.
因为onsaveinstancestate()默认的实现有助于节省用户界面的状态,如果重写的方法,节省额外的状态信息,你应该总是做任何工作之前调用父类的实现onsaveinstancestate()。同样的,你也应该如果重写它调用的实现onrestoreinstancestate() ,所以默认实现可以还原视图状态。
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的状态)-你不应该使用它来存储数据持久性。相反,你应该使用onpause()存储持久性数据(如数据应保存到数据库)当用户离开activity。
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以应用替代资源,可用于新的屏幕配置。仅仅出于这个原因,它是非常重要的,你的活动完全恢复状态时,它是重现,因为用户在使用应用程序定期旋转屏幕。
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,由于屏幕方向改变重新启动,如上面所描述的恢复活动状态,你的应用在acitivity生命周期中对于其他突发性事件,更具弹性的。
The best way to handle such a restart is to save and restore the state of your activity usingonSaveInstanceState()
and onRestoreInstanceState()
(or onCreate()
),
as discussed in the previous section.
最好的办法来处理这样的重新启动是保存和恢复你的活动和使用onsaveinstancestate() onrestoreinstancestate()(或oncreate()),如在上一节讨论。
For more information about configuration changes that happen at runtime and how you can handle them, read the guide to Handling Runtime Changes.
在运行时配置发生改变,更多的信息和如何处理它们,阅读处理运行改变的指导。
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重建之前,第一个acitiviy会不会完全停止的,而不是第二个activity的进程覆盖了第一个activity的进程。
The order of lifecycle callbacks is well defined, particularly when the two activities are in the same process and one is starting the other. Here‘s the order of operations that occur when Activity A starts Acivity B:
生命周期回调的顺序是明确的,特别是当两个Activity是同一个进程中,一个activity启动另外一个activity的时候。活动开始活动B的操作顺序:
Activity A‘s onPause()
method executes.
Activity A的onpause()方法执行。
Activity B‘s onCreate()
, onStart()
,
and onResume()
methods execute in sequence. (Activity B now has user focus.)
activityB的oncreate(),onstart(),和onresume()方法执行的顺序。(activityB有用户焦点。)
Then, if Activity A is no longer visible on screen, its onStop()
method
executes.
然后,如果activity不再是显示在屏幕上,它的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读取数据库,你应该在onPause()写入数据库,而不是onStop()。
标签:
原文地址:http://blog.csdn.net/mikky_android/article/details/51943617