原文地址:https://developer.android.com/training/basics/activity-lifecycle/starting
--------------------------------------------------------------------------------------------------------------------
Unlike other programming paradigms in which apps are launched with a main()
method, the Android system initiates code in anActivity
instance by invoking specific callback methods that correspond to specific stages of its lifecycle. There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity.
和其他以main()启动的编程范例不同,Android系统在一个Activity 实例中初始化代码,它调用了一系列对应于生命周期中特定阶段的特定回调函数。一个activity由一个回调函数序列开始,并且以一系列回调函数结束。
This lesson provides an overview of the most important lifecycle methods and shows you how to handle the first lifecycle callback that creates a new instance of your activity.
本课提供了一个有关最重要的生命周期函数的概览,向你展示怎样控制第一个生命周期回调函数(它用于创建你的activity的一个新的实例)。
Understand the Lifecycle Callbacks — 理解生命周期回调函数
During the life of an activity, the system calls a core set of lifecycle methods in a sequence similar to a step pyramid. That is, each stage of the activity lifecycle is a separate step on the pyramid. As the system creates a new activity instance, each callback method moves the activity state one step toward the top. The top of the pyramid is the point at which the activity is running in the foreground and the user can interact with it.
在一个activity的生命活动中,系统按照一定次序调用一系列核心的生命周期函数,这与一个梯形金字塔很相似。也就是说,activity生命活动中的每个阶段都是金字塔中的一个单独的步骤。当系统创建一个新的activity时,每个回调函数将朝着顶部,由一个活动状态转移到另一个活动状态。在金字塔的顶部,该activity在前台运行,用户可以和它进行交互。
As the user begins to leave the activity, the system calls other methods that move the activity state back down the pyramid in order to dismantle the activity. In some cases, the activity will move only part way down the pyramid and wait (such as when the user switches to another app), from which point the activity can move back to the top (if the user returns to the activity) and resume where the user left off.
当用户开始离开该activity时,系统调用另外一些方法,使得活动状态向金字塔下方转换以便拆除该activity。在一些情况下,该activity将仅仅部分向下移动然后等待(例如当用户切换到另一个app),在该点活activity可以返回金字塔顶部(如果用户返回该activity)并且从用户之前中断的地方重新开始。
Depending on the complexity of your activity, you probably don't need to implement all the lifecycle methods. However, it's important that you understand each one and implement those that ensure your app behaves the way users expect. Implementing your activity lifecycle methods properly ensures your app behaves well in several ways, including that it:
- Does not crash if the user receives a phone call or switches to another app while using your app.
- Does not consume valuable system resources when the user is not actively using it.
- Does not lose the user's progress if they leave your app and return to it at a later time.
- Does not crash or lose the user's progress when the screen rotates between landscape and portrait orientation.
取决于你的activity的复杂性,你可能不需要实现所有的回调函数。但是,理解每个函数是非常重要的,并且实现这些可以保证你的app按照用户期望的方式运行。实现你的activity生命周期函数可以合适地保证你的app在一些方面表现良好,包括:
- 在使用你的app时,如果用户接到一个电话或是切换到另一个app,它不会crash。
- 在用户没有活跃地使用它时,它不会消耗系统资源。
- 如果用户离开你的app并且之后返回它时,它不会丢失用户进程。
- 当屏幕旋转时,它不会crash或是丢失用户进程。
As you'll learn in the following lessons, there are several situations in which an activity transitions between different states that are illustrated in figure 1. However, only three of these states can be static. That is, the activity can exist in one of only three states for an extended period of time:
- Resumed
- In this state, the activity is in the foreground and the user can interact with it. (Also sometimes referred to as the "running" state.)
- Paused
- In this state, the activity is partially obscured by another activity—the other activity that's in the foreground is semi-transparent or doesn't cover the entire screen. The paused activity does not receive user input and cannot execute any code.
- Stopped
- In this state, the activity is completely hidden and not visible to the user; it is considered to be in the background. While stopped, the activity instance and all its state information such as member variables is retained, but it cannot execute any code.
(第一句不翻译了)但是,只有3个状态是静态的。也就是说,一个activity在持续期间只能停留在以下三种状态中一种:
The other states (Created and Started) are transient and the system quickly moves from them to the next state by calling the next lifecycle callback method. That is, after the system callsonCreate()
, it quickly callsonStart()
, which is quickly followed byonResume()
.
其他的状态(Created和Started)是瞬时的,系统通过调用下一个生命周期回调函数,从它们快速地转移到另一个状态。也就是说,系统调用 onCreate()后,它立刻调用onStart(),然后再迅速调用onResume()。
That's it for the basic activity lifecycle. Now you'll start learning about some of the specific lifecycle behaviors.
Specify Your App's Launcher Activity —— 定义你自己的App的启动活动
When the user selects your app icon from the Home screen, the system calls theonCreate()
method for theActivity
in your app that you've declared to be the "launcher" (or "main") activity. This is the activity that serves as the main entry point to your app's user interface.
当从Home屏幕用户选择你的app图标时,系统将为你的app中声明为 "launcher" (或者"main") activity的Activity调用onCreate()
方法。这个activity承担了你的app的用户界面的主程序入口。
You can define which activity to use as the main activity in the Android manifest file,AndroidManifest.xml
, which is at the root of your project directory.
你可以定义哪个activity为main activity在Android的清单文件中,AndroidManifest.xml
,这是你项目目录的根。
The main activity for your app must be declared in the manifest with an <intent-filter>
that includes the MAIN
action andLAUNCHER
category. For example:
这个main activity一定在清单中以一个<intent-filter>
声明,包含了MAINaction和LAUNCHER
category。例如:
<activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter></activity>
Note: When you create a new Android project with the Android SDK tools, the default project files include anActivity
class that's declared in the manifest with this filter.
注意:当你使用Android SDK工具创建一个Android项目时,默认的项目文件包含一个Activity类,并在清单使用这个filter被声明。
If either the MAIN
action orLAUNCHER
category are not declared for one of your activities, then your app icon will not appear in the Home screen's list of apps.
如果 MAIN
action 和LAUNCHER
category 都没有在你的activities中被声明,那么你的app图标将不会出现在Home屏幕的app列表中。
Create a New Instance —— 创建一个新的实例
Most apps include several different activities that allow the user to perform different actions. Whether an activity is the main activity that's created when the user clicks your app icon or a different activity that your app starts in response to a user action, the system creates every new instance of Activity
by calling itsonCreate()
method.
大多数apps包含了一些不同的activities来允许用户进行不同的行为。对于任何的一个activity,系统通过调用onCreate() 方法创建每一个Activity 的实例。
You must implement the onCreate()
method to perform basic application startup logic that should happen only once for the entire life of the activity. For example, your implementation of onCreate()
should define the user interface and possibly instantiate some class-scope variables.
你必须实现onCreate() 方法,来执行基本的应用程序启动逻辑(只在activity的整个生命活动中发生一次)。例如,你的onCreate() 的实现应该定义了用户界面并且可能实例化一下类的变量。
For example, the following example of the onCreate()
method shows some code that performs some fundamental setup for the activity, such as declaring the user interface (defined in an XML layout file), defining member variables, and configuring some of the UI.
例如,下面的onCreate() 方法的例子展示了一下代码,它执行了一些关于activity的基本设置,例如声明用户界面(在一个XML布局文件中定义),定义成员变量,并且配置了一些UI。
TextView mTextView; // Member variable for text view in the layout 布局中的一个文本编辑框的成员变量 @Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the user interface layout for this Activity 设置用户界面 // The layout file is defined in the project res/layout/main_activity.xml file 布局文件定义在项目中的res/layout/main_activity.xml文件 setContentView(R.layout.main_activity); // Initialize member TextView so we can manipulate it later 初始化成员TextView以便后面我们可以操纵它 mTextView = (TextView) findViewById(R.id.text_message); // Make sure we're running on Honeycomb or higher to use ActionBar APIs 确保我们正运行在Honeycomb或是更高来使用ActionBar APIs if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // For the main activity, make sure the app icon in the action bar 对于main activity,确保app图标在action bar中 // does not behave as a button 不是表现为一个按键 ActionBar actionBar = getActionBar(); actionBar.setHomeButtonEnabled(false); }}
Caution: Using the SDK_INT
to prevent older system's from executing new APIs works in this way on Android 2.0 (API level 5) and higher only. Older versions will encounter a runtime exception.
Once the onCreate()
finishes execution, the system calls theonStart()
andonResume()
methods in quick succession. Your activity never resides in the Created or Started states. Technically, the activity becomes visible to the user when onStart()
is called, butonResume()
quickly follows and the activity remains in the Resumed state until something occurs to change that, such as when a phone call is received, the user navigates to another activity, or the device screen turns off.
一旦onCreate()完成执行,系统紧接着调用onStart()
和onResume()方法。你的activity不会停留在Created或者Started状态。技术上,活动在
onStart()调用后才变得对用户可见,但是onResume()紧紧相随然后activity停留在Resumed状态直到某些事件发生来改变它,例如当接到一个电话,用户导航到另一个activity,或者设备屏幕关闭了。
In the other lessons that follow, you'll see how the other start up methods, onStart()
andonResume()
, are useful during your activity's lifecycle when used to resume the activity from the Paused or Stopped states.
在接下来的其他课程中,你将会看到其他的回调函数怎样开始方法,当需要从Paused或者Stopped状态重新开始时,onStart() 和onResume()在你的activity的生命周期中会很有用。
Note: The onCreate()
method includes a parameter calledsavedInstanceState
that's discussed in the latter lesson about Recreating an Activity.
注意:onCreate() 方法包含了一个叫做savedInstanceState的参数,这个我们将在接下来的关于Recreating an Activity的课程中讨论
Destroy the Activity —— 销毁活动
While the activity's first lifecycle callback is onCreate()
, its very last callback isonDestroy()
. The system calls this method on your activity as the final signal that your activity instance is being completely removed from the system memory.
activity的第一个生命周期回调函数是onCreate(),而它的最后一个回调函数是onDestroy()。系统调用该方法作为一个最终信号,你的activity实例将要被完全从系统内存中清除。
Most apps don't need to implement this method because local class references are destroyed with the activity and your activity should perform most cleanup duringonPause()
andonStop()
. However, if your activity includes background threads that you created duringonCreate()
or other long-running resources that could potentially leak memory if not properly closed, you should kill them duringonDestroy()
.
大多数apps不需要实现这个方法,因为随着你的activity,局部的类引用类型将随之销毁,并且你的activity在 onPause()
andonStop()期间完成了大部分清理工作。但是,如果你的activity包含了后台线程(在onCreate()中创建)或者其他长期执行的资源,如果没有合适地关闭就有可能造成内存泄露,你应该在onDestroy()中结束它们。
@Overridepublic void onDestroy() { super.onDestroy(); // Always call the superclass // Stop method tracing that the activity started during onCreate() 停止方法追踪(该活动在onCreate()中开始) android.os.Debug.stopMethodTracing();}
Note: The system calls onDestroy()
after it has already calledonPause()
andonStop()
in all situations except one: when you callfinish()
from within theonCreate()
method. In some cases, such as when your activity operates as a temporary decision maker to launch another activity, you might call finish()
from withinonCreate()
to destroy the activity. In this case, the system immediately callsonDestroy()
without calling any of the other lifecycle methods.
注意:除了一种情况外,系统在所有情况下,都是在已经调用了onPause() 和onStop()
后再调用onDestroy()。这种情况是:当你在onCreate()中调用finish()方法。在一些情况下,例如当你的activity运行为一个暂时的决策人来启动另一个activity,你可能在onCreate()中调用finish()来销毁该activity。在这种情况下,系统立刻调用onDestroy(),不再调用其他任何生命周期函数。