Starting an Activity 启动一个Activity
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.
Android系统启动代码不像其他编程范式的应用是通过一个main()方法运行的,它是对应于特定的生命周期的阶段在一个通过调用特定的回调方法的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只有一部分沿着金字塔(如当用户切换到另一个应用程序),从某个点的activity搬回顶部(如果用户返回到活动)和恢复avtivity,。
A simplified illustration of the Activity lifecycle, expressed as a step pyramid. This shows how, for every callback used to take the activity a step toward the Resumed state at the top, there's a callback method that takes the activity a step down. The activity can also return to the resumed state from the Paused and Stopped state.
活动的生命周期的一个简化的例子,表示为一个阶梯金字塔。这表明,每回调用于在顶部把活动一步恢复状态,有一个以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:
取决于你的activity的复杂性,您可能不需要实现所有生命周期方法。然而,重要的是你了解并且实施那些确保应用程序行为和用户期望的方式。实现你的正常activity生命周期方法可以确保你在应用程序的几个方面的行为,包括:
- 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.
- 当屏幕在横向和纵向之间旋转时,不崩溃或失去用户的进程。
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:
您将学习以下课程,某些情况下,一个activity有不同的状态之间的转换。然而,只有三个状态可以是静态的。也就是说,只有三个状态的activity可以存在一段时间:
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.
在这种状态下,activity主要被前景是半透明或不覆盖整个屏幕的其他活动掩盖。暂停活动不接受用户输入,并不能执行任何代码。
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.
在这种状态下,该活动是完全隐藏的,对用户不可见的,它被认为是在后台。停止时,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().
其他状态(创建并启动)瞬态和系统通过调用下一个生命周期回调方法迅速从他们到下一个状态转移。即在系统callsonCreate(),它迅速callsonStart(),随后很快byonResume()。
That's it for the basic activity lifecycle. Now you'll start learning about some of the specific lifecycle behaviors.
这就是它的基本activity生命周期。现在你会学习一些特定的生命周期的行为。
Specify Your App's Launcher Activity 指定应用程序的启动活动
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.
当用户从主屏幕选择应用程序图标时,系统为所有在你的应用程序调用onCreate()方法,您已经宣布activity的“launcher”(或“main”)activity。这是activity作为你的应用程序的主要入口点的用户界面。
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.
您可以在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:
你的应用程序的主要活动必须声明是在一个声明包括LAUNCHER类别,包括主要的行动的< intent-filter >清单中。例如:
<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.
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.
注意:当您使用Android SDK工具,默认项目文件包括Activity类创建一个新的Android项目时,在这个过滤器的清单中声明。如果主要动作orLAUNCHER类别不声明你的activity,应用程序图标将不会出现在主屏幕上的应用程序的列表中。
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.
大多数应用程序都包括几个不同的活动,允许用户执行不同的操作。当用户单击应用程序图标或一个不同的活动时,创建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 ofonCreate() should define the user interface and possibly instantiate some class-scope variables.
你必须启动逻辑只会发生一次的活动实现onCreate()方法来执行基本的应用程序。例如,实现onCreate()应该定义用户界面和实例化一些class-scope变量。
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()方法显示了一些代码,执行一些基本设置的活动,如声明用户界面(XML布局文件中定义),定义成员变量和配置的一些UI。
TextView mTextView; // Member variable for text view in the layout
@Override
public 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
setContentView(R.layout.main_activity);
// Initialize member TextView so we can manipulate it later
mTextView = (TextView) findViewById(R.id.text_message);
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// For the main activity, make sure the app icon in the action bar
// does not behave as a button
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
}
}
Caution: Using the SDK_INT to prevent older systems 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.
警告:使用SDK_INT以这种方式工作在Android 2.0(API级别5)和更高防止旧系统执行新的API。旧版本将遇到一个运行时异常。
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 whenonStart() 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()执行完成后,系统调用theonStart()和onResume接二连三地执行。你的活动永远驻留在创建或开始。从技术上讲,活动变得可见,用户onStart()时,onResume()快速跟随,活动仍在恢复状态,直到事情发生改变,例如当收到一个电话,用户导航到另一个活动,或设备屏幕关闭。
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.
在接下来的其他课程,您将看到如何启动方法,在你活动的生命周期恢复暂停或停止的活动状态onStart()和onResume(),使用时是有用的。
Note: The onCreate() method includes a parameter calledsavedInstanceState that's discussed in the latter lesson aboutRecreating an Activity.
注意:onCreate()方法包含一个参数calledsavedInstanceState,在Recreating an Activity中涉及。
Another illustration of the activity lifecycle structure with an emphasis on the three main callbacks that the system calls in sequence when creating a new instance of the activity:onCreate(),onStart(), andonResume(). Once this sequence of callbacks complete, the activity reaches the Resumed state where users can interact with the activity until they switch to a different activity.
活动生命周期结构在创建一个新实例的活动的另一个例子强调的三个主要的回调系统调用序列:onCreate(),onStart(),onResume()。一旦这一系列的回调函数完成,活动达到恢复状态,用户可以活动,直到他们交互切换到一个不同的活动。
Destroy the Activity 销毁activity
While the activity's first lifecycle callback is onCreate(), its very last callback is onDestroy(). The system calls this method on your activity as the final signal that your activity instance is being completely removed from the system memory.
在活动的第一个生命周期回调onCreate(),其最后的回调是onDestroy()。系统对你的活动调用这个方法作为最后一个信号,表明你的活动实例是完全从系统内存中删除。
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().
大多数应用程序不需要实现这个方法,因为当地类在onPause()和onStop()之间引用被破坏的活动和你的活动应该执行大多数清理。然而,如果你的活动包括后台线程创建duringonCreate()或其他长期资源,如果没有正确关闭可能会泄漏内存,你应该在onDestroy()杀了他们。
@Override
public void onDestroy() {
super.onDestroy(); // Always call the superclass
// Stop method tracing that the activity started during 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 callfinish() from withinonCreate() to destroy the activity. In this case, the system immediately callsonDestroy() without calling any of the other lifecycle methods.
注意:系统调用onDestroy()后,onPause()和onStop()执行在所有情况下,只有一个除外:当你从内部onCreate()方法finish()。在某些情况下,例如当你的活动是一个临时的决策者推出另一个活动,你可能从onCreate()调用finish()来破坏活动。在这种情况下,系统立即调用任何其他生命周期方法onDestroy()。